publicsynchronizedvoidprintA(){ for (int i = 0; i < 10; i++) { while (flag != 0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("A"); flag = 1; notifyAll(); } }
/** * 输出B方法 */ publicsynchronizedvoidprintB(){ for (int i = 0; i < 10; i++) { while (flag != 1){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("B"); flag = 2; notifyAll(); } } publicsynchronizedvoidprintC(){ for (int i = 0; i < 10; i++) { while (flag != 2){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("C"); flag = 0; notifyAll(); }
}
publicstaticvoidmain(String[] args){ final TestThreadDemo2 demo = new TestThreadDemo2(); synchronized (demo){ new Thread(()->demo.printA()).start(); new Thread(()->demo.printB()).start(); new Thread(()->demo.printC()).start(); } } }