同时三个线程启动分别打印a、b、c, 要求按照循序打印abcabcabc
使用wait notify两个关键字实现。
代码如下:
public class Test14 {
// 交替打印
public static void main(String[] args) {
WaitNotify waitNotify = new WaitNotify(1,3);
new Thread(() -> {
waitNotify.printf("a",1,2);
},"t1").start();
new Thread(() -> {
waitNotify.printf("b",2,3);
},"t2").start();
new Thread(() -> {
waitNotify.printf("c",3,1);
},"t3").start();
}
}
class WaitNotify {
// 打印函数
public void printf(String str, int flag, int waitNum) {
for (int i = 0; i < this.waitNum; i++) {
synchronized (this) {
while (flag != this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.print(str);
this.flag = waitNum;
this.notifyAll();
}
}
}
// 构造函数 初始化打印状态以及循环次数
public WaitNotify(int flag, int waitNum) {
this.flag = flag;
this.waitNum = waitNum;
}
// 打印标记
private int flag;
// 循环几次
private int waitNum;
}
运行结果:
个人学习记录!