目录
主要方法
- wait(); 线程等待
- notify(); 通知一个等待的线程
- notifyAll(); 通知所有等待的线程
一、主程序
package xyz.jangle.thread.test.n2_3.synccondition;
import java.util.concurrent.TimeUnit;
/**
*
* 在synchronized代码块中使用条件
* @author jangle
* @email jangle@jangle.xyz
* @time 2021年1月29日 上午3:01:23
*
*/
public class M2 {
private Object lock = new Object();
public static void main(String[] args) throws Exception {
M2 m2 = new M2();
new Thread(() -> {
m2.test1();
}).start();
TimeUnit.SECONDS.sleep(1);
m2.test2();
new Thread(() -> {
m2.test4();
}).start();
TimeUnit.SECONDS.sleep(1);
m2.test3();
}
public synchronized void test1() {
System.out.println("test1 start");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test1 end");
}
public synchronized void test2() {
System.out.println("test2 start");
notifyAll();
System.out.println("test2 end");
}
public void test3() {
System.out.println("test3 start");
synchronized (lock) {
lock.notify();
}
System.out.println("test3 end");
}
public void test4() {
synchronized (lock) {
System.out.println("test4 start");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test4 end");
}
}
}
二、执行结果
test1 start
test2 start
test2 end
test1 end
test4 start
test3 start
test3 end
test4 end

该博客展示了如何在Java中使用`synchronized`关键字和条件变量进行线程同步。通过`wait()`、`notify()`和`notifyAll()`方法,实现了线程间的通信和协作。示例中,`test1()`线程被`test2()`唤醒,而`test4()`线程由`test3()`通知。

被折叠的 条评论
为什么被折叠?



