场景
编写一个程序,启动三个线程,三个线程的name分别是A,B,C;,每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC...
使用 synchronized 实现
public class MyService { private int flag = 1; public synchronized void printA(){ while (flag != 1) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(Thread.currentThread().getName()); flag = 2; this.notifyAll(); } public synchronized void printB(){ while (flag != 2) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(Thread.currentThread().getName()); flag = 3; this.notifyAll(); } public synchronized void printC(){ while (flag != 3) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(Thread.currentThread().getName()); flag = 1; this.notifyAll(); } }