Java多线程问题

peter20091001 peter20091001 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

public class ThreadA {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadB b = new ThreadB();
b.start();
synchronized(b){
try {
System.out.println("this is a thread");
b.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("b.total="+b.total);
}

}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized (this) {
for(int i = 0;i < 10;i ++) {
total +=i;
System.out.println(i);
}
notify();
}
}
}

这段代码运行结果是
this is a thread
1
2
3
4
5
6
7
8
9
b.total=45
红色的这段代码和ThreadB.run()方法中的代码都加了synchronized,为什么先执行红色的这段,后执行ThreadB?
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
peter20091001
Java SE 62,620 成员 307,251 内容