两个线程交替运行——使用synchronized+wait+notify实现

public class ExecuteThread {
private static Object obj = new Object();
private static boolean flag; // 默认是false

public static void main(String[] args) {
new Thread(new Runnable() { // 匿名内部类
@Override
public void run() {
synchronized (obj) {
for (int i = 0; i < 10; i++) {
if (flag) {
try {
obj.wait(); // 释放锁进入等待队列(等待池),线程2获取到对象锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notify(); // 唤醒等待队列中线程2进入锁池竞争对象锁
flag = true;
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
}, "thread1").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (obj) {
for (int i = 0; i < 10; i++) {
if (!flag) {
try {
obj.wait(); // 释放锁进入等待队列(等待池),线程1获取到对象锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notify(); // 唤醒等待队列中线程1进入锁池竞争对象锁
flag = false;
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
}, "thread2").start();
}
}
原文地址:https://www.cnblogs.com/coderxiaobai/p/12887375.html