/** * 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
猜你喜欢
转载自blog.csdn.net/czj1992czj/article/details/80168510
今日推荐
周排行