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;
}
}
...全文
6630 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kinlymg 2021-07-02
  • 打赏
  • 举报
回复

Thread t = new MyThread(n);
Thread t2 = new MyThread(n);
两个线程的欧式wait

Y.ue 2020-08-15
  • 打赏
  • 举报
回复
引用 3 楼 大隐藏于寺 的回复:
以后发帖的时候尽量把代码写在[code=语言类型]代码内容[/code]里面
今天重新看了下你的代码,你线程2还是MyThread对象,应该new 一个MyThread2对象


谢谢你,其实刚发完这个贴我就看到错误,就立刻结贴了。 不过这种错误真的好难发现,你这个方法很实用!谢谢啦
大隐藏于寺 2020-08-11
  • 打赏
  • 举报
回复
以后发帖的时候尽量把代码写在[code=语言类型]代码内容[/code]里面 今天重新看了下你的代码,你线程2还是MyThread对象,应该new 一个MyThread2对象
大隐藏于寺 2020-08-10
  • 打赏
  • 举报
回复
正好刚才回复了类似的问题,看看这里
securitit 2020-08-10
  • 打赏
  • 举报
回复 2
wait操作阻塞在哪里,被唤醒时,就从哪里开始执行。

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧