Java實現使用 3 個執行緒 a,b,c 實現輪流交替輸出字串的每個字元,並顯示行號。
阿新 • • 發佈:2022-03-27
1、問題:Java實現使用 3 個執行緒 a,b,c 實現輪流交替輸出字串的每個字元,並顯示行號。
2、程式碼實現(執行緒池方式)
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Code4 { /** 使用 3 個執行緒 a,b,c 實現輪流交替輸出字串的每個字元,並顯示行號。 控制檯顯示效果如下: (執行緒 a,b,c 也需要按照順序輸出) 1.執行緒 a 輸出字元: ~ 2.執行緒 b 輸出字元: a 3.執行緒 c 輸出字元: s 4.執行緒 a 輸出字元: d 5.執行緒 b 輸出字元: ; 6.執行緒 c 輸出字元: 4 7.執行緒 a 輸出字元: # 8.執行緒 b 輸出字元: 1 9.執行緒 c 輸出字元: e 10.執行緒 a 輸出字元: r */ //列印字串的鎖 private static final Object LOCK = new Object(); //控制列印位置的指標 private static volatile int index = 0; //列印的執行緒池 static ExecutorService executor = Executors.newFixedThreadPool(3); public static void main(String[] args) { String str = "~asd;4#1er&67qwe234#1&3sdBd1d1,@3ret#1&56ghk123#1A&34D"; String[] strs = str.split(""); executor.execute(() -> { try { printStringA(strs); } catch (InterruptedException e) { e.printStackTrace(); } }); executor.execute(() -> { try { printStringB(strs); } catch (InterruptedException e) { e.printStackTrace(); } }); executor.execute(() -> { try { printStringC(strs); } catch (InterruptedException e) { e.printStackTrace(); } }); executor.shutdown(); } public static void printStringA(String[] strs) throws InterruptedException { while (strs.length > index) { synchronized (LOCK) { if (index % 3 == 0) { //1.執行緒 a 輸出字元:~ System.out.println( (index+1) + ".執行緒 a 輸出字元: " +strs[index]); index++; // notify 隨機喚醒一個持有該鎖的其他執行緒 LOCK.notify(); } else { // 阻塞當前執行緒 LOCK.wait(); } } } } public static void printStringB(String[] strs) throws InterruptedException { while (strs.length > index) { synchronized (LOCK) { if (index % 3 == 1) { System.out.println( (index+1) + ".執行緒 b 輸出字元: " +strs[index]); index++; LOCK.notify(); } else { LOCK.wait(); } } } } public static void printStringC(String[] strs) throws InterruptedException { while (strs.length > index) { synchronized (LOCK) { if (index % 3 == 2) { System.out.println( (index+1) + ".執行緒 c 輸出字元: " +strs[index]); index++; LOCK.notify(); } else { LOCK.wait(); } } } } }
3、思路擴充套件