新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
五種判斷線程池任務執(zhí)行完成的方式
Thread線程是否執(zhí)行完成,我們可以調用join方法然后等待線程執(zhí)行完成;那在使用線程池的時候,我們?nèi)绾沃谰€程已經(jīng)執(zhí)行完成了?本文就帶給大家五種判斷的方式:

- isTerminated() 方式,在執(zhí)行 shutdown() ,關閉線程池后,判斷是否所有任務已經(jīng)完成。
- ThreadPoolExecutor 的 getCompletedTaskCount() 方法,判斷完成任務數(shù)和全部任務數(shù)是否相等。
- CountDownLatch計數(shù)器,使用閉鎖計數(shù)來判斷是否全部完成。
- 手動維護一個公共計數(shù) ,原理和閉鎖類似,就是更加靈活。
- 使用submit向線程池提交任務,F(xiàn)uture判斷任務執(zhí)行狀態(tài)。
方法一:isTerminated()
測試代碼
package pool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 方法一:isTerminated
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> sleepMethod(index));
}
pool.shutdown();
while (!pool.isTerminated()){
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
}上述代碼處理邏輯在主線程中進行循環(huán)判斷,全部任務是否已經(jīng)完成。
這里有兩個主要方法:
- shutdown() :對線程池進行有序關閉。調用該方法后,線程池將不再接受新的任務,但會繼續(xù)執(zhí)行已提交的任務。如果線程池已經(jīng)處于關閉狀態(tài),則對該方法的調用沒有額外的作用。
- isTerminated() :判斷線程池中的所有任務是否在關閉后完成。只有在調用了shutdown()或shutdownNow()方法后,所有任務執(zhí)行完畢,才會返回true。需要注意的是,在調用shutdown()之前調用isTerminated()方法始終返回false。
優(yōu)缺點分析
優(yōu)點 :操作簡單。
缺點 :需要關閉線程池。并且日常使用是將線程池注入到Spring容器,然后各個組件中統(tǒng)一用同一個線程池,不能直接關閉線程池。
方法二:getCompletedTaskCount()
測試代碼
package pool;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 方法二:getCompletedTaskCount
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> sleepMethod(index));
}
//當線程池完成的線程數(shù)等于線程池中的總線程數(shù)
while (!(pool.getTaskCount() == pool.getCompletedTaskCount())) {
System.out.println("任務總數(shù):" + pool.getTaskCount() + "; 已經(jīng)完成任務數(shù):" + pool.getCompletedTaskCount());
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
}上述代碼處理邏輯還是一樣在主線程循環(huán)判斷,主要就兩個方法:
- getTaskCount() :返回計劃執(zhí)行的任務總數(shù)。由于任務和線程的狀態(tài)可能在計算過程中動態(tài)變化,返回的值只是一個近似值。這個方法返回的是線程池提交的任務總數(shù),包括已經(jīng)完成和正在執(zhí)行中的任務。
- getCompletedTaskCount() :返回已經(jīng)完成執(zhí)行的任務的大致總數(shù)。由于任務和線程的狀態(tài)可能在計算過程中動態(tài)改變,返回的值只是一個近似值,并且在連續(xù)的調用中不會減少。這個方法返回的是已經(jīng)完成執(zhí)行的任務數(shù)量,不包括正在執(zhí)行中的任務。
優(yōu)缺點分析
- 優(yōu)點 :不必關閉線程池,避免了創(chuàng)建和銷毀帶來的損耗。
- 缺點 :使用這種判斷存在很大的限制條件;必須確定在循環(huán)判斷過程中沒有新的任務產(chǎn)生。
方法三:CountDownLatch
測試代碼
package pool;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 方法三:CountDownLatch
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//計數(shù)器,判斷線程是否執(zhí)行結束
CountDownLatch taskLatch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> {
sleepMethod(index);
taskLatch.countDown();
System.out.println("當前計數(shù)器數(shù)量:" + taskLatch.getCount());
});
}
//當前線程阻塞,等待計數(shù)器置為0
taskLatch.await();
System.out.println("全部執(zhí)行完畢");
}
}優(yōu)缺點分析
優(yōu)點 :代碼優(yōu)雅,不需要對線程池進行操作。
缺點 :需要提前知道線程數(shù)量;性能較差;還需要在線程代碼塊內(nèi)加上異常判斷,否則在 countDown之前發(fā)生異常而沒有處理,就會導致主線程永遠阻塞在 await。
方法四:公共計數(shù)
測試代碼
package pool;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int taskNum = 0; //計數(shù)器
/**
* 方法四:公共計數(shù)
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Lock lock = new ReentrantLock();
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> {
sleepMethod(index);
lock.lock();
taskNum++;
lock.unlock();
});
}
while(taskNum < 10) {
Thread.sleep(1000);
System.out.println("還沒停止。。。當前完成任務數(shù):" + taskNum);
}
System.out.println("全部執(zhí)行完畢");
}
}這種實現(xiàn)其實就是通過加鎖計數(shù),然后循環(huán)判斷。
優(yōu)缺點分析
- 優(yōu)點 :手動維護方式更加靈活,對于一些特殊場景可以手動處理。
- 缺點 :和CountDownLatch相比,一樣需要知道線程數(shù)目,但是代碼實現(xiàn)比較麻煩。
方法五:Future
測試代碼
package pool;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 方法五:Future
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Future future = pool.submit(() -> sleepMethod(1));
while (!future.isDone()){
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
}優(yōu)缺點分析
優(yōu)點:使用簡單,不需要關閉線程池。
缺點:每個提交給線程池的任務都會關聯(lián)一個Future對象,這可能會引入額外的內(nèi)存開銷。如果需要處理大量的任務,可能會占用較多的內(nèi)存。
測試代碼匯總
package pool;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 五種判斷線程池任務執(zhí)行完成的方式
* @author 百里
*/
public class BaiLiIsShutdownThreadPoolDemo {
/**
* 創(chuàng)建一個最大線程數(shù)15的線程池
*/
public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
10,
15,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10));
/**
* 線程執(zhí)行方法,隨機等待0到10秒
*/
private static void sleepMethod(int index){
try {
long sleepTime = new Double(Math.random() * 10000).longValue();
Thread.sleep(sleepTime);
System.out.println("當前線程執(zhí)行結束: " + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 方法一:isTerminated
* @param args
* @throws InterruptedException
*/
public static void isTerminatedTest(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> sleepMethod(index));
}
pool.shutdown();
while (!pool.isTerminated()){
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
/**
* 方法二:getCompletedTaskCount
* @param args
* @throws InterruptedException
*/
public static void completedTaskCountTest(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> sleepMethod(index));
}
//當線程池完成的線程數(shù)等于線程池中的總線程數(shù)
while (!(pool.getTaskCount() == pool.getCompletedTaskCount())) {
System.out.println("任務總數(shù):" + pool.getTaskCount() + "; 已經(jīng)完成任務數(shù):" + pool.getCompletedTaskCount());
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
/**
* 方法三:CountDownLatch
* @throws Exception
*/
public static void countDownLatchTest(String[] args) throws Exception {
//計數(shù)器,判斷線程是否執(zhí)行結束
CountDownLatch taskLatch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> {
sleepMethod(index);
taskLatch.countDown();
System.out.println("當前計數(shù)器數(shù)量:" + taskLatch.getCount());
});
}
//當前線程阻塞,等待計數(shù)器置為0
taskLatch.await();
System.out.println("全部執(zhí)行完畢");
}
private static int taskNum = 0;
/**
* 方法四:公共計數(shù)
* @throws Exception
*/
public static void countTest(String[] args) throws Exception {
Lock lock = new ReentrantLock();
for (int i = 0; i < 10; i++) {
int index = i;
pool.execute(() -> {
sleepMethod(index);
lock.lock();
taskNum++;
lock.unlock();
});
}
while(taskNum < 10) {
Thread.sleep(1000);
System.out.println("還沒停止。。。當前完成任務數(shù):" + taskNum);
}
System.out.println("全部執(zhí)行完畢");
}
/**
* 方法五:Future
* @throws Exception
*/
public static void futureTest(String[] args) throws Exception {
Future future = pool.submit(() -> sleepMethod(1));
while (!future.isDone()){
Thread.sleep(1000);
System.out.println("還沒停止。。。");
}
System.out.println("全部執(zhí)行完畢");
}
} 新聞標題:五種判斷線程池任務執(zhí)行完成的方式
分享路徑:http://m.fisionsoft.com.cn/article/cdoojdp.html


咨詢
建站咨詢
