用多執行緒完成一個小題目(續)
阿新 • • 發佈:2020-07-01
接著上次的來講,就是用兩個執行緒,輸出1a2b3c4d5e ...
又發現了一種新的實現方式,相對來說也更簡單點。
主要是通過LockSupport來實現,話不多說,上程式碼:
public class CommunicationC { static char[] num = {'1', '2', '3', '4', '5', '6'}; static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f'}; boolean flag = true; ThreadOne threadOne = new ThreadOne(); ThreadTwo threadTwo= new ThreadTwo(); public static void main(String[] args) { for (int i = 0; i < 10; i++) { new CommunicationC().run(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }public void run() { threadOne.start(); threadTwo.start(); } class ThreadOne extends Thread { @Override public void run() { for (char i : num) { if (flag) { System.out.print(i); flag = false; LockSupport.unpark(threadTwo); LockSupport.park(); } } } }class ThreadTwo extends Thread { @Override public void run() { for (char i : chars) { LockSupport.park(); if (!flag) { System.out.print(i); flag = true; LockSupport.unpark(threadOne); } } } } }
輸出結果:
通過LockSupport的park和unpark來控制執行緒的通訊,相對來說說更簡單直觀點,後續還有更有趣的方式也可以放上來,以此記錄下。