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