
主线程和子线程交替执行的线程同步
本问题要求实现主线程和子线程交替执行100次和10次的循环。提供的代码使用 synchronized 和 wait()/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();
}
}
}
}
}修改说明:
以上就是主线程和子线程交替执行,代码为何无法正常运行以及如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号