Java如何判斷線程是否結(jié)束的三種方法
方法1
通過Thread類中的isAlive()方法判斷線程是否處于活動狀態(tài)。
線程啟動后,只要沒有運(yùn)行完畢,都會返回true。
【注】如果只是要等其他線程運(yùn)行結(jié)束之后再繼續(xù)操作,可以執(zhí)行t.join(),即:在t執(zhí)行完畢前掛起。
方法2
通過Thread.activeCount()方法判斷當(dāng)前線程的線程組中活動線程的數(shù)目,為1時其他線程運(yùn)行完畢。
方法3
通過java.util.concurrent.Executors中的方法創(chuàng)建一個線程池,用這個線程池來啟動線程。啟動所有要啟動的線程后,執(zhí)行線程池的shutdown()方法,即在所有線程執(zhí)行完畢后關(guān)閉線程池。然后通過線程池的isTerminated()方法,判斷線程池是否已經(jīng)關(guān)閉。線程池成功關(guān)閉,就意味著所有線程已經(jīng)運(yùn)行完畢了。
import java.util.concurrent.ExecutorService; ? import java.util.concurrent.Executors; ? public class Test { ? ? ? ? public static void main(String args[]) throws InterruptedException { ? ? ? ? ? ExecutorService exe = Executors.newFixedThreadPool(50); ? ? ? ? ? for (int i = 1; i <= 5; i++) { ? ? ? ? ? ? ? exe.execute(new SubThread(i)); ? ? ? ? ? } ? ? ? ? ? exe.shutdown(); ? ? ? ? ? while (true) { ? ? ? ? ? ? ? if (exe.isTerminated()) { ? ? ? ? ? ? ? ? ? System.out.println("結(jié)束了!"); ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? } ? ? ? ? ? ? ? Thread.sleep(200); ? ? ? ? ? } ? ? ? } ? }
判斷線程池中的線程是否全部執(zhí)行完畢的另外一種解決方案則是使用閉鎖(CountDownLatch)來實現(xiàn),CountDownLatch是一種靈活的閉鎖實現(xiàn),它可以使一個或多個線程等待一組事件發(fā)生。閉鎖狀態(tài)包括一個計數(shù)器,該計數(shù)器被初始化為一個正數(shù),表示需要等待的事件數(shù)量。countDown方法遞減計數(shù)器,表示有一個事件已經(jīng)發(fā)生了,而await方法等待計數(shù)器達(dá)到零,即表示需要等待的事情都已經(jīng)發(fā)生。可以使用閉鎖來這樣設(shè)計程序達(dá)到目的:
public class CountDownLatchApproach {undefined public static void main(String[] args) throws IOException, InterruptedException {undefined final int nThreads = 10; final CountDownLatch endGate = new CountDownLatch(nThreads); final File stream = new File("c:\\temp\\stonefeng\\stream.txt"); final OutputStream os = new FileOutputStream(stream); final OutputStreamWriter writer = new OutputStreamWriter(os); ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < nThreads; i++) {undefined final int num = i; Runnable task = new Runnable() {undefined @Override public void run() {undefined try {undefined writer.write(String.valueOf(num)+"\n"); } catch (IOException e) {undefined e.printStackTrace(); } finally {undefined endGate.countDown(); } } }; exec.submit(task); } endGate.await(); writer.write("---END---\n"); writer.close(); } }
到此這篇關(guān)于Java如何判斷線程是否結(jié)束的三種方法的文章就介紹到這了,更多相關(guān)Java 判斷線程結(jié)束內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
elasticsearch開發(fā)中data-streams使用解析
這篇文章主要為大家介紹了elasticsearch開發(fā)中data-streams使用解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08排查Failed?to?validate?connection?com.mysql.cj.jdbc.Connec
這篇文章主要介紹了Failed?to?validate?connection?com.mysql.cj.jdbc.ConnectionImpl問題排查,具有很好的參考價值,希望對大家有所幫助2023-02-02SpringAop切入點execution表達(dá)式的深入講解
Spring AOP 可能會經(jīng)常使用 execution切入點指示符,下面這篇文章主要給大家介紹了關(guān)于SpringAop切入點execution表達(dá)式的相關(guān)資料,需要的朋友可以參考下2021-08-08MyBatis-Plus QueryWrapper及LambdaQueryWrapper的使用詳解
這篇文章主要介紹了MyBatis-Plus QueryWrapper及LambdaQueryWrapper的使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03