package net.jasonjiang.thread;import java.io.IOException; public class ThreadTestNew { public static void main(String[] args) throws IOException { final Test obj = new Test(); new Thread() { public void run() { obj.m1(); } }.start(); new Thread() { public void run() { obj.m2(); } }.start(); new Thread() { public void run() { obj.m3(); } }.start(); } } class Test { volatile int target = 1; public synchronized void m1() { for (int i = 0; i < 10; i++) { while (target == 2 || target == 3) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("m1() =" + i); target = 2; notifyAll(); } } public synchronized void m2() { for (int i = 0; i < 10; i++) { while (target == 1 || target == 3) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("m2() =" + i); target = 3; notifyAll(); } } public synchronized void m3() { for (int i = 0; i < 10; i++) { while (target == 1 || target == 2) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("m3() =" + i); target = 1; notifyAll(); } } }
运行结果:
m1() =0m2() =0m3() =0m1() =1m2() =1m3() =1m1() =2m2() =2m3() =2m1() =3m2() =3m3() =3m1() =4m2() =4m3() =4m1() =5m2() =5m3() =5m1() =6m2() =6m3() =6m1() =7m2() =7m3() =7m1() =8m2() =8m3() =8m1() =9m2() =9m3() =9