寫兩個線程,其中一個線程列印1-52,另一個線程列印A-Z,列印順序應該是12A34B56C......5152Z。 該習題需要用到多線程通信的知識。 思路分析: 把列印數字的線程稱為線程N,列印字母的線程稱為線程L. 1.線程N完成列印後,需要等待,通知線程L列印;同理,線程L列印後,也需要等待, ...
寫兩個線程,其中一個線程列印1-52,另一個線程列印A-Z,列印順序應該是12A34B56C......5152Z。
該習題需要用到多線程通信的知識。
思路分析:
把列印數字的線程稱為線程N,列印字母的線程稱為線程L.
1.線程N完成列印後,需要等待,通知線程L列印;同理,線程L列印後,也需要等待,並通知線程N列印
線程的通信可以利用Object的wait和notify方法。
2.兩個線程在執行各自的列印方法的時候,不應該被打斷,所以把列印方法設置成同步的方法。
3.兩個線程何時停止列印?當兩個線程的列印方法都執行了26次的時候。
實現:
1.PrintStr類,用來完成列印,擁有printNumber和printLetter兩個同步方法
1 package pratise.multithreading; 2 3 public class { 4 5 private int flag=0; 6 private int beginIndex=1; 7 private int beginLetter=65; 8 9 private int nCount=0; 10 private int lCount=0; 11 12 public int getnCount() 13 { 14 return nCount; 15 } 16 17 public int getlCount() 18 { 19 return lCount; 20 } 21 22 public synchronized void printNumber() 23 { 24 try { 25 if(flag==0) 26 { 27 nCount++; 28 System.out.print(beginIndex); 29 System.out.print(beginIndex+1); 30 beginIndex+=2; 31 //改標誌位 32 flag++; 33 //喚醒另一個線程 34 notify(); 35 }else 36 { 37 wait(); 38 } 39 } catch (InterruptedException e) { 40 e.printStackTrace(); 41 } 42 43 } 44 45 public synchronized void printLetter() 46 { 47 try { 48 if(flag==1) 49 { 50 lCount++; 51 char letter=(char)beginLetter; 52 System.out.print(String.valueOf(letter)); 53 beginLetter++; 54 flag--; 55 notify(); 56 }else 57 { 58 wait(); 59 60 } 61 } catch (InterruptedException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } 65 66 67 } 68 69 }
2.兩個線程類,分別包含一個PrintStr對象
1 package pratise.multithreading; 2 3 public class PrintNumberThread extends Thread { 4 private PrintStr ps; 5 public PrintNumberThread(PrintStr ps) 6 { 7 this.ps=ps; 8 } 9 10 public void run() 11 { 12 13 while(ps.getnCount()<26) 14 { 15 ps.printNumber(); 16 } 17 } 18 }
1 package pratise.multithreading; 2 3 public class PrintLetterThread extends Thread { 4 private PrintStr ps; 5 public PrintLetterThread(PrintStr ps) 6 { 7 this.ps=ps; 8 } 9 10 public void run() 11 { 12 while(ps.getlCount()<26) 13 { 14 ps.printLetter(); 15 } 16 } 17 }
3.含有main方法的類,用來啟動線程。
1 package pratise.multithreading; 2 3 public class PrintTest { 4 5 public static void main(String[] args) { 6 PrintStr ps=new PrintStr(); 7 new PrintNumberThread(ps).start(); 8 new PrintLetterThread(ps).start(); 9 } 10 11 }