public class PrintABC {
private static final Object lock = new Object();
private static volatile Integer index = 0;
private static final int count = 3;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print(i + "A");
index++;
lock.notifyAll();
}
}
}, "a-thread");
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print("B");
index++;
lock.notifyAll();
}
}
}, "b-thread");
Thread t3 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (index % count != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
System.out.print("C");
index++;
lock.notifyAll();
}
}
}, "c-thread");
t1.start();
t2.start();
t3.start();
}
标签:index,ABC,Thread,++,lock,打印,InterruptedException,线程,catch
From: https://www.cnblogs.com/d9e84208/p/18020744