1 package rainbow.thread; 2 3 public class PrintABC { 4 5 private int counta = 0, countb = 0, countc = 0; 6 7 private boolean printa = false, printb = false, printc = false; 8 9 private int printcount = 0; 10 11 public void printa(){ 12 synchronized(this){ 13 while(!(printcount == 0 || (printb && printc))){ 14 try { 15 wait(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 System.out.println("A"); 21 printa = true; 22 //reset 23 printb = printc = false; 24 counta++; 25 printcount++; 26 try { 27 Thread.sleep(1000); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 notifyAll(); 32 } 33 } 34 35 public void printb(){ 36 synchronized(this){ 37 while(!printa || (counta - countb == 0)){ 38 try { 39 wait(); 40 } catch (InterruptedException e) { 41 e.printStackTrace(); 42 } 43 } 44 System.out.println("B"); 45 printb = true; 46 countb++; 47 printcount++; 48 try { 49 Thread.sleep(1000); 50 } catch (InterruptedException e) { 51 e.printStackTrace(); 52 } 53 notifyAll(); 54 } 55 } 56 57 public void printc(){ 58 synchronized(this){ 59 while(!printb || (countb - countc == 0)){ 60 try { 61 wait(); 62 } catch (InterruptedException e) { 63 e.printStackTrace(); 64 } 65 } 66 System.out.println("C"); 67 printc = true; 68 //reset a 69 printa = false; 70 countc++; 71 printcount++; 72 try { 73 Thread.sleep(1000); 74 } catch (InterruptedException e) { 75 e.printStackTrace(); 76 } 77 notifyAll(); 78 } 79 80 } 81 82 public int getPrintcount() { 83 return printcount; 84 } 85 86 public void setPrintcount(int printcount) { 87 this.printcount = printcount; 88 } 89 90 }
1 package rainbow.thread; 2 3 public class PrintThread implements Runnable { 4 5 private PrintABC abc = null; 6 7 public PrintThread(PrintABC abc){ 8 this.abc = abc; 9 } 10 11 public void run() { 12 while(abc.getPrintcount() <= 30){ 13 abc.printa(); 14 } 15 } 16 17 }
1 package rainbow.thread; 2 3 public class TestThread { 4 5 public static void main(String[] args) { 6 PrintABC abc = new PrintABC(); 7 8 new Thread(new PrintThread(abc)).start(); 9 new Thread(new PrintThread1(abc)).start(); 10 new Thread(new PrintThread2(abc)).start(); 11 } 12 13 }