class Useless {
public static boolean b = true;
public synchronized void u1() {
try {
while (b == true)
wait();
} catch (InterruptedException i) {
}
}
public synchronized void u2() {
if (b == true) {
b = false;
}
notify();
}
}
public class SleepMessages extends Thread {
private Useless u;
public SleepMessages(Useless u) {
this.u = u;
}
public void run() {
String importantInfo[] = { "Mares eat oats", "Does eat oats" };
for (int i = 0; i < importantInfo.length; i++) {
u.u1();
System.out.println(importantInfo[i] + " - " + getName());
try {
sleep(2000);
} catch (InterruptedException e) {
}
}
}
public static void main(String args[]) throws InterruptedException {
Useless u = new Useless();
Thread t1 = new SleepMessages(u);
t1.setName("t1");
Thread t2 = new SleepMessages(u);
t2.setName("t2");
t1.start();
t2.start();
sleep(2000);
System.out.println("Here they go!...");
t1.interrupt();
sleep(1000);
t2.interrupt();
u.u2();
sleep(1000);
u.u2();
}
}
这个小程序的输出给出: 他们来了!... 母马吃燕麦 - t1 母马吃燕麦 - t2 吃燕麦吗-t2 吃燕麦吗 - t1
我的问题是为什么线程 t2 是唯一进入 catch(InterruptedException e) 的线程,为什么结果不是这样的:
他们来了!... 母马吃燕麦 - t1 母马吃燕麦 - t2 吃燕麦吗 - t1 吃燕麦吗 - t2
最佳答案
My question is why does the thread t2 is the only one that enters the catch(InterruptedException e),
在我看来,t1.interrupt()
正在中断 run() 方法中的 sleep 。一旦丢弃 InterruptedException,就无法知道线程之前是否被中断过。
why isn't the result something like this: Here they go!... Mares eat oats - t1 Mares eat oats - t2 Does eat oats - t1 Does eat oats - t2
Java 使用偏向锁定。这意味着最后一个获取锁的线程更有可能首先获取相同的锁。
关于Java多线程使用 sleep 和中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14219306/