Created
August 31, 2011 13:46
-
-
Save greghmerrill/1183567 to your computer and use it in GitHub Desktop.
Illustrates the fact that Thread.stop() won't immediately stop a Thread which is waiting to acquire a lock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
This illustrates the fact that calling stop() on a Thread | |
won't stop the Thread if it's waiting on a monitor. | |
The output I get is: | |
Thread t1 acquiring lock | |
Thread t1 has lock | |
Thread t2 acquiring lock | |
...waits forever... | |
If you remove t2.join(), you will find that t2 does in fact get stopped, | |
but only after t1 is stopped. | |
By contrast, if you stop/join t1 first, you get: | |
Thread t1 acquiring lock | |
Thread t1 has lock | |
Thread t2 acquiring lock | |
t1 alive? false | |
t2 alive? false | |
*/ | |
public class StopThreadWhileAcquiringLock { | |
public static void main(String[] args) throws Exception { | |
Runnable r = new Runnable() { | |
@Override | |
public void run() { | |
System.out.println("Thread " + Thread.currentThread().getName() + " acquiring lock"); | |
acquireLock(); | |
} | |
}; | |
Thread t1 = new Thread(r, "t1"); | |
Thread t2 = new Thread(r, "t2"); | |
t1.start(); | |
Thread.sleep(100); | |
t2.start(); | |
Thread.sleep(100); | |
t2.stop(); | |
t2.join(); | |
t1.stop(); | |
t1.join(); | |
System.out.println("t1 alive? " + t1.isAlive()); | |
System.out.println("t2 alive? " + t2.isAlive()); | |
} | |
public static synchronized void acquireLock() { | |
System.out.println("Thread " + Thread.currentThread().getName() + " has lock"); | |
while (true) { } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment