Query regarding Thread.Interrupt

  • Thread starter Russell Stuart via .NET 247
  • Start date
R

Russell Stuart via .NET 247

I always though .Net monitors were meant to be similar to thejava synchronisation mechanisms. The code below proves mewrong. When run under the debugger, it produces just "Thread 1"lines, as I expected. But when run without the debugger itproduced both "Thread 1" and "Thread 2" lines, impling that twothreads are executing in the same lock region. I though thatwasn't supposed to happen. Am I wrong?


using System;
using System.Threading;

public class Test
{
Thread t1, t2;

public void Run1()
{
Thread.Sleep(1000);
lock (this)
{
Monitor.Pulse(this);
t2.Interrupt();
for (;;)
Console.WriteLine("Thread 1");
}
}

public void Run2()
{
lock (this)
{
try
{
Monitor.Wait(this);
}
catch (ThreadInterruptedException)
{
Console.WriteLine("2 Interrupted");
}
for (;;)
Console.WriteLine("Thread 2");
}
}

public void Go()
{
t1 = new Thread(new ThreadStart(Run1));
t2 = new Thread(new ThreadStart(Run2));
t1.Start();
t2.Start();
}

public static void Main()
{
new Test().Go();
}
}
 
J

Jon Skeet [C# MVP]

Russell Stuart via .NET 247 said:
I always though .Net monitors were meant to be similar to the java
synchronisation mechanisms. The code below proves me wrong. When run
under the debugger, it produces just "Thread 1" lines, as I expected.
But when run without the debugger it produced both "Thread 1" and
"Thread 2" lines, impling that two threads are executing in the same
lock region. I though that wasn't supposed to happen. Am I wrong?

It looks like it's a bug (or at least strange behaviour) of thread
interruption. There's a good reason Thread.interrupt is deprecated in
Java - it's basically a dodgy thing to use, IMO!
 
R

Russell Stuart

There's a good reason Thread.interrupt is deprecated in
Java - it's basically a dodgy thing to use, IMO!

Thread.interrupt is not deprecated in Java. Its pretty
safe to use because it re-acquires the lock before
aborting the wait().
 
J

Jon Skeet [C# MVP]

Russell Stuart said:
Thread.interrupt is not deprecated in Java. Its pretty
safe to use because it re-acquires the lock before
aborting the wait().

My apologies - I was thinking of Thread.stop(). Doh!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top