如何實現有三個執行緒a,b,c,這三個執行緒都有一個方法分別列印A、B、C,問怎麼能實現列印10次ABC的功能,實現方案包括三種,分別為執行緒池、鎖標誌和join方法。
方法一:執行緒池
public class ThreadTest { public static void main(String[] args) { //執行緒池方式 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor() ; int times = 10 ; for(int i=0; i<times; i++) { singleThreadExecutor.execute(new ThreadA()); singleThreadExecutor.execute(new ThreadB()); singleThreadExecutor.execute(new ThreadC()); } singleThreadExecutor.shutdown(); } public static class ThreadA implements Runnable { @Override public void run() { System.out.println("A Thread, print A"); } } public static class ThreadB implements Runnable { @Override public void run() { System.out.println("B Thread, print B"); } } public static class ThreadC implements Runnable { @Override public void run() { System.out.println("C Thread, print C"); } }}
方案二:ReetrantLock實現
public class ThreadTest2 { private static Lock lock = new ReentrantLock() ; private static int state = 0; public static void main(String[] args) { new Thread(new ThreadA()).start(); new Thread(new ThreadB()).start(); new Thread(new ThreadC()).start(); } public static class ThreadA implements Runnable { @Override public void run() { for(int i=0; i<10;) { try { lock.lock(); if(state % 3 == 0) { System.out.println("Thread A: print A"); state ++ ; i++; } } finally { lock.unlock(); } } } } public static class ThreadB implements Runnable { @Override public void run() { for(int i=0; i<10;) { try { lock.lock(); if(state % 3 == 1) { System.out.println("Thread B: print B"); state ++ ; i++; } } finally { lock.unlock(); } } } } public static class ThreadC implements Runnable { @Override public void run() { for(int i=0; i<10;) { try { lock.lock(); if(state % 3 == 2) { System.out.println("Thread C: print C"); state ++ ; i++; } } finally { lock.unlock(); } } } }}
方案三:join實現
public class ThreadTest3 { public static void main(String[] args) throws InterruptedException { for(int i=0; i<10; i++) { Thread a = new Thread(new ThreadA()) ; Thread b = new Thread(new ThreadB()) ; Thread c = new Thread(new ThreadC()) ; a.start(); a.join(); b.start(); b.join(); c.start(); c.join(); } } public static class ThreadA implements Runnable { @Override public void run() { System.out.println("A Thread, print A"); } } public static class ThreadB implements Runnable { @Override public void run() { System.out.println("B Thread, print B"); } } public static class ThreadC implements Runnable { @Override public void run() { System.out.println("C Thread, print C"); } }}
熱門排行
- GC類壓力管道安裝資質辦理,氨製冷(冷庫)管道定期檢驗程序
- 幾種PCBA表面處理的類型
- 歌禮制藥-B(01672)宣佈口服PD-L1小分子抑制劑前藥ASC61 用於治療晚期實體瘤的美國I期臨床試驗完成首例患者給藥
- 深耕CRO服務領域 宣泰醫藥(688247.SH)擬首次公開發行4534萬股
- 壓力容器許可證資質辦理,鉻鉬鋼製壓力容器結構設計規定
- 家裡有點地,這種果樹種上兩棵,栽到花盆裡,夏天就能結果子
- 家裡養株“大將軍”蘭花,花色喜慶,花大如盆,打理很簡單
- 庫存飆升!韓國半導體庫存激增80%
- 多點DMALL合夥人劉桂海:多點DMALL實踐實體零售數字化轉型
- 豬各階段拉稀的原因和解決方案,這篇文章告訴你答案,值得收藏