間隔打印A,B:
public class Print { private boolean nowIsA =true; synchronized void printA() throws InterruptedException { // 注意點:如果使用if,會使此處 處於wait狀態線程被喚醒, // 狀態改變沒有及時響應直接往下執行,可能 出現重複打印A或B; // 使用while可以再次校驗; // wait:釋放鎖 // notify:不是馬上釋放鎖,執行完才釋放 ,容易出現死鎖,用notifyAll解決 while (!nowIsA){ this.wait(); } System.out.println("A A A A A"); nowIsA = false; this.notify(); } synchronized void printB() throws InterruptedException { while (nowIsA){ this.wait(); } System.out.println("B B B B B"); nowIsA =true; this.notify(); } }
public class A extends Thread { private Print p; public A(Print p) { this.p = p; } @Override public void run() { super.run(); while (true){ try { p.printA(); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class B extends Thread { private Print p; public B(Print p) { this.p = p; } @Override public void run() { super.run(); while (true){ try { p.printB(); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Client { public static void main(String[] args) { Print print = new Print(); A[]a = new A[5]; B[]b = new B[5]; for(int i=0;i<5;i++){ a[i]= new A(print); a[i].start(); b[i]= new B(print); b[i].start(); } } }
打印效果:
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A
B B B B B
A A A A A