public class Demo {
public static void main(String[] args) {
ShareData sd = new ShareData();
new Thread(() -> {
for (int i = 0; i < 10; i++)
sd.printA();
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++)
sd.printB();
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++)
sd.printC();
}, "C").start();
}
static class ShareData {
private static int num = 30;
public synchronized void printA() {
// 判断
while (num % 3 != 0) {
try {
// 进入锁池
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 干活
num--;
System.out.println(Thread.currentThread().getName());
// 通知
// 把锁池里的线程放入等待池
this.notifyAll();
}
public synchronized void printB() {
// 判断
while (num % 3 != 2) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 干活
num--;
System.out.println(Thread.currentThread().getName());
// 通知
this.notifyAll();
}
public synchronized void printC() {
// 判断
while (num % 3 != 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 干活
num--;
System.out.println(Thread.currentThread().getName());
// 通知
this.notifyAll();
}
}
}
交替打印三个线程
最新推荐文章于 2022-03-29 21:06:20 发布