实现此功能的方式有好几种,我这里只是最简单的其中一种.
Synchronized无法实现唤醒指定的线程,即便如此,虽然通过notifyAll唤醒了所有线程,但是只有满足条件的线程才可以继续执行,不满足条件的线程,即便被唤醒了还是会继续wait.
如果通过Lock方式实现这个功能,那么可以唤醒指定的线程.
package com.infuq.thread.d3;
public class SynchronizedVersion {
public static void main(String[] args) {
Print print = new Print();
// 循环打印20次 最终结果:ABCABCABCABC...
new Thread(() -> { for (int i = 0; i < 20; i++) print.printA(); }, "A").start();
new Thread(() -> { for (int i = 0; i < 20; i++) print.printB(); }, "B").start();
new Thread(() -> { for (int i = 0; i < 20; i++) print.printC(); }, "C").start();
}
static class Print {
private int state = 0;
synchronized void printA() {
while (state % 3 != 0) {// 即便执行此段代码的线程被唤醒,但是不满足它的条件,它依然会继续wait
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
state++;
System.out.println("A");
// 唤醒所有的线程
notifyAll();
}
synchronized void printB() {
while (state % 3 != 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
state++;
System.out.println("B");
notifyAll();
}
synchronized void printC() {
while (state % 3 != 2) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
state++;
System.out.println("C");
notifyAll();
}
}
}
公众号