Java:寫2個執行緒,其中一個執行緒列印1-52,另一個執行緒列印A-Z,列印順序應該是12A34B56C...5152Z。
阿新 • • 發佈:2018-11-23
寫2個執行緒,其中一個執行緒列印1-52,另一個執行緒列印A-Z,列印順序應該是12A34B56C...5152Z
多執行緒程式設計:使用Runnable介面例項建立執行緒。使用執行緒等待方法wait();
package com.java瘋狂講義; public class Print { //flag==true時,列印數字; private boolean flag = true; //要列印數字的起始數 private int num = 0; public synchronized void printNumber() throws InterruptedException { if (!flag) { this.wait(); } for (int i = 0; i < 2; i++) { System.out.println(++num + "\t"); } flag = false; this.notify(); } public synchronized void printChar(int i) throws InterruptedException { if (flag) { this.wait(); } System.out.println((char)('A' + i )+ "\t"); flag = true; this.notify(); } }
測試類:
package com.java瘋狂講義; public class Test { public static void main(String[] args){ Print print = new Print(); new Thread(new Runnable() { @Override public void run() { for(int i =0;i<26;i++){ try{ print.printNumber(); }catch(InterruptedException e){ e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i =0;i<26;i++){ try{ print.printChar(i); }catch(InterruptedException e){ e.printStackTrace(); } } } }).start(); } }