
线程同步、synchronized 和锁
这篇问答文章探讨了 java 中线程同步和同步机制的实现,重点介绍了 synchronized 关键字和锁的使用。
在给出的代码中,主线程和子线程交替执行,每执行 100 或 10 次后通知另一个线程继续执行。
问题:
立即学习“Java免费学习笔记(深入)”;
代码存在以下问题:
解决方案:
将问题代码修改如下:
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();
}
}
}
}
}这些修改解决了原有代码中的问题:
以上就是Java 线程同步:如何解决主线程和子线程无法交替执行的问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号