/**
* Created by jenkin
*/
public class ThreadPrintABC {
int atomicInteger = 0;
public void printfABC() {
Object lock = new Object();
Thread thread = new Thread(() -> {
while (true) {
synchronized (lock) {
if (atomicInteger % 3 == 0) {
System.out.println("A");
atomicInteger++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread1 = new Thread(() -> {
while (true) {
synchronized (lock) {
if (atomicInteger % 3 == 1) {
System.out.println("B");
atomicInteger++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread2 = new Thread(() -> {
while (true) {
synchronized (lock) {
if (atomicInteger % 3 == 2) {
System.out.println("C");
atomicInteger++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
thread1.start();
thread2.start();
}
public static void main(String[] args) {
ThreadPrintABC threadPrintABC = new ThreadPrintABC();
threadPrintABC.printfABC();
}
}
三个线程分别打印A,打印B,打印C
最新推荐文章于 2022-08-12 12:29:17 发布