日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!!

發(fā)布時間:2025/3/21 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!! 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

newSingleThreadExecutor 這個線程池,保證線程里面的任務(wù)依次執(zhí)行,這讓我發(fā)現(xiàn)了新大陸,

立馬實踐了一下,發(fā)現(xiàn)不負(fù)所望;

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 第一反應(yīng)的解決方法,事實證明不可靠//t1.start();//t2.start();//t3.start();// method 2 使用 單個任務(wù)的線程池來實現(xiàn)。保證線程的依次執(zhí)行ExecutorService executor = Executors.newSingleThreadExecutor();executor.submit(t1);executor.submit(t2);executor.submit(t3);executor.shutdown();} }

在這里發(fā)現(xiàn)結(jié)果每次都是 t1執(zhí)行,t2執(zhí)行,t3執(zhí)行,這里達(dá)到目的了之后,不禁回想,這個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>()));}

這個實例化的意思我嘗試翻譯了一下,意思就是創(chuàng)建一個只有一個線程的線程池來操作不限數(shù)量的隊列,也就是把線程放進了一個隊列中,隊列我們都知道是FIFO的(LinkedBlockingQueue)。SingleThreadExecutor的工作線程只有一個,其他隊列中的線程都處于休眠,也就是sleep狀態(tài),當(dāng)這個worker線程做完事了,也就是run方法運行結(jié)束,就又從隊列中拿出一個休眠線程(sleep)出來喚醒(notify),這樣依次把隊列中的所有線程處理完畢,這樣并沒有結(jié)束,如果線程池中沒有待處理的線程,線程池一直會等待,等待下一次任務(wù)的提交,除非把線程池給shutdown掉,這樣線程池的生命周期才算完畢。

總結(jié)

以上是生活随笔為你收集整理的多线程:保证三个线程依次按顺序执行?newSingleThreadExecutor!!!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。