多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!!
生活随笔
收集整理的這篇文章主要介紹了
多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!!
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
newSingleThreadExecutor 這個線程池,保證線程里面的任務依次執行,這讓我發現了新大陸,
立馬實踐了一下,發現不負所望;
public class TestJoin {public static void main(String[] args) throws InterruptedException {final Thread t1 = new Thread(new Runnable() {public void run() {System.out.println(Thread.currentThread().getName() + " run 1");}}, "T1");final Thread t2 = new Thread(new Runnable() {public void run() {System.out.println(Thread.currentThread().getName() + " run 2");try {t1.join(10);} catch (InterruptedException e) {e.printStackTrace();}}}, "T2");final Thread t3 = new Thread(new Runnable() {public void run() {System.out.println(Thread.currentThread().getName() + " run 3");try {t2.join(10);} catch (InterruptedException e) {e.printStackTrace();}}}, "T3");// method1 第一反應的解決方法,事實證明不可靠//t1.start();//t2.start();//t3.start();// method 2 使用 單個任務的線程池來實現。保證線程的依次執行ExecutorService executor = Executors.newSingleThreadExecutor();executor.submit(t1);executor.submit(t2);executor.submit(t3);executor.shutdown();} }在這里發現結果每次都是 t1執行,t2執行,t3執行,這里達到目的了之后,不禁回想,這個Single線程池為啥這么好用,不由得就像把線程池狠狠的看一遍,然后就去翻看了源代碼
/*** Creates an Executor that uses a single worker thread operating* off an unbounded queue. (Note however that if this single* thread terminates due to a failure during execution prior to* shutdown, a new one will take its place if needed to execute* subsequent tasks.) Tasks are guaranteed to execute* sequentially, and no more than one task will be active at any* given time. Unlike the otherwise equivalent* {@code newFixedThreadPool(1)} the returned executor is* guaranteed not to be reconfigurable to use additional threads.** @return the newly created single-threaded Executor*/public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}這個實例化的意思我嘗試翻譯了一下,意思就是創建一個只有一個線程的線程池來操作不限數量的隊列,也就是把線程放進了一個隊列中,隊列我們都知道是FIFO的(LinkedBlockingQueue)。SingleThreadExecutor的工作線程只有一個,其他隊列中的線程都處于休眠,也就是sleep狀態,當這個worker線程做完事了,也就是run方法運行結束,就又從隊列中拿出一個休眠線程(sleep)出來喚醒(notify),這樣依次把隊列中的所有線程處理完畢,這樣并沒有結束,如果線程池中沒有待處理的線程,線程池一直會等待,等待下一次任務的提交,除非把線程池給shutdown掉,這樣線程池的生命周期才算完畢。
總結
以上是生活随笔為你收集整理的多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多线程:为什么wait()需要放在循环中
- 下一篇: 多线程:当你提交任务时,线程队列已经满了