【Java並發】線程的順序執行

來源:互聯網
上載者:User

標籤:service   dex   java   executor   方式   ...   submit   bsp   string   

 1 /** 2  * 問題:有線程a、b、c,如何讓它們順序執行? 3  * 方式一:可用Join()方法實現 4  * 方式二:可用newSingleThreadExecutor() 5  * Created by Smile on 2018/8/12. 6  */ 7 public class ThreadByOrder { 8  9     public static void main(String[] args) throws InterruptedException {10 11         Thread a = new Thread(new ThreadTest("a"));12         Thread b = new Thread(new ThreadTest("b"));13         Thread c = new Thread(new ThreadTest("c"));14 15         //方式一實現16         a.start();17         a.join();18         b.start();19         b.join();20         c.start();21 22         Thread d = new Thread(new ThreadTest("c"));23         Thread e = new Thread(new ThreadTest("d"));24         Thread f = new Thread(new ThreadTest("e"));25         //方式二實現26         ExecutorService singlePool = Executors.newSingleThreadExecutor();27         singlePool.submit(d);28         singlePool.submit(e);29         singlePool.submit(f);30         singlePool.shutdown();31     }32 33     static class ThreadTest implements Runnable{34 35         private String threadName;36 37         public ThreadTest(String name){38             this.threadName = name;39         }40 41         public ThreadTest() {42         }43 44         public void run() {45             if("a".equals(threadName)||"f".equals(threadName))46                 try {47                     Thread.sleep(5000);48                 } catch (InterruptedException e) {49                     e.printStackTrace();50                 }51             System.out.println("thread "+threadName+" is running...");52         }53     }54 }

 

【Java並發】線程的順序執行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.