主线程和子线程交替执行,代码为何无法正常运行以及如何解决?
你在学习文章相关的知识吗?本文《主线程和子线程交替执行,代码为何无法正常运行以及如何解决?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

主线程和子线程交替执行的线程同步
本问题要求实现主线程和子线程交替执行100次和10次的循环。提供的代码使用 synchronized 和 wait()/notify() 实现线程同步,但存在一些问题导致程序无法正常运行。
问题原因:
- 主线程的 wait() 方法放在了 finally 块中,导致 wait() 方法无法在 notify() 方法调用后释放锁。
- 子线程的 wait() 方法的锁对象不是 me 而是 this,导致子线程无法被主线程的 notify() 方法唤醒。
修改后的代码:
public class Test_02 {
public static void main(String[] args) {
MeThread me = new MeThread();
Thread t = new Thread(me);
t.start();
boolean flag = true;
int i = 0; // 修改了初始值
synchronized (me) {
while (flag) {
System.out.println(Thread.currentThread().getName() + i);
i++;
if (i % 100 == 0) {
try {
// 方便观察效果,睡眠1s
Thread.sleep(1000);
System.out.println("main============");
// 从 finally 代码块中前移到 wait() 方法前
me.notify();
// 锁对象为 me
me.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class MeThread implements Runnable {
@Override
public synchronized void run() {
int i = 0;
boolean flag = true;
while (flag) {
System.out.println(Thread.currentThread().getName() + i);
i++;
if (i % 10 == 0) {
try {
// 方便观察
Thread.sleep(1000);
System.out.println("MeThread============");
// 同步方法锁对象为 this, notify() 移动到 wait() 方法前
this.notify();
// 同步方法锁对象为 this
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
修改说明:
- 将主线程的 wait() 方法移动到 notify() 方法之后。
- 同步方法 run() 的锁对象改为 this,确保主线程和子线程使用相同的锁。
今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
