
线程同步、synchronized 和锁
这篇问答文章探讨了 java 中线程同步和同步机制的实现,重点介绍了 synchronized 关键字和锁的使用。
在给出的代码中,主线程和子线程交替执行,每执行 100 或 10 次后通知另一个线程继续执行。
问题:
立即学习“Java免费学习笔记(深入)”;
代码存在以下问题:
- 主线程和子线程无法交替执行,而是一直由主线程执行。
- notify() 方法放在了 finally 代码块中,可能无法正确唤醒另一个线程。
解决方案:
将问题代码修改如下:
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();
}
}
}
}
}这些修改解决了原有代码中的问题:
- 初始化 i 的值为 0,确保两个线程从头开始执行。
- 将 notify() 方法从 finally 代码块移至 wait() 方法之前,确保在 wait() 之前唤醒另一个线程。
- 在 synchronized 块中使用 me 作为锁对象,以正确同步两个线程对 i 的访问。
- 在 methread 的 run() 方法中使用 this 作为锁对象,以正确同步该线程对 i 变量的访问。










