JAVA中测试wait被唤醒后,线程从头开始执行还是紧接着wait执行,遇到问题
Y.ue 2020-08-09 08:17:16 //测试wait被唤醒后线程从哪里开始执行
/*t1启动 打印t1begin ,然后wait,释放锁Num n 。
t2启动 , 打印t2begin ,然后notifyAll ,应当打印t2over,结束run后,
t1可重新拿到锁,应当打印t1over。
但程序卡住,未打印t2over,与t1over,说明notifyAll后,程序就卡住了,这是为何。*/
public class WaitTest {
public static void main(String[] args) {
Num n = new Num(10);
Thread t = new MyThread(n);
Thread t2 = new MyThread(n);
t.setName("t1");
t2.setName("t2");
t.start();
//确保t1在t2前运行
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyThread extends Thread{
Num n;
public MyThread(Num n) {
this.n = n;
}
@Override
public void run() {
synchronized (n){
System.out.println(currentThread().getName() + "begin");
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currentThread().getName() + "over");
}
}
}
class MyThread2 extends Thread{
Num n;
public MyThread2(Num n) {
this.n = n;
}
@Override
public void run() {
synchronized (n) {
System.out.println(currentThread().getName() + "begin");
n.notifyAll();
System.out.println(currentThread().getName() + "over");
}
}
}
class Num{
int num;
public Num(int num) {
this.num = num;
}
}