Java線程池的幾種完成辦法和差別引見。本站提示廣大學習愛好者:(Java線程池的幾種完成辦法和差別引見)文章只能為提供參考,不一定能成為您想要的結果。以下是Java線程池的幾種完成辦法和差別引見正文
Java線程池的幾種完成辦法和差別引見
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThreadPool {
// -newFixedThreadPool與cacheThreadPool差不多,也是能reuse就用,但不克不及隨時建新的線程
// -其奇特的地方:隨意率性時光點,最多只能有固定命目標運動線程存在,此時假如有新的線程要樹立,只能放在別的的隊列中期待,直到以後的線程中某個線程終止直接被移出池子
// -和cacheThreadPool分歧,FixedThreadPool沒有IDLE機制(能夠也有,但既然文檔沒提,確定異常長,相似依附下層的TCP或UDP
// IDLE機制之類的),所以FixedThreadPool多半針對一些很穩固很固定的正軌並發線程,多用於辦事器
// -從辦法的源代碼看,cache池和fixed 池挪用的是統一個底層池,只不外參數分歧:
// fixed池線程數固定,而且是0秒IDLE(無IDLE)
// cache池線程數支撐0-Integer.MAX_VALUE(明顯完整沒斟酌主機的資本蒙受才能),60秒IDLE
private static ExecutorService fixedService = Executors.newFixedThreadPool(6);
// -緩存型池子,先檢查池中有無之前樹立的線程,假如有,就reuse.假如沒有,就建一個新的線程參加池中
// -緩存型池子平日用於履行一些生計期很短的異步型義務
// 是以在一些面向銜接的daemon型SERVER頂用得不多。
// -能reuse的線程,必需是timeout IDLE內的池中線程,缺省timeout是60s,跨越這個IDLE時長,線程實例將被終止及移出池。
// 留意,放入CachedThreadPool的線程不用擔憂其停止,跨越TIMEOUT不運動,其會主動被終止。
private static ExecutorService cacheService = Executors.newCachedThreadPool();
// -單例線程,隨意率性時光池中只能有一個線程
// -用的是和cache池和fixed池雷同的底層池,但線程數量是1-1,0秒IDLE(無IDLE)
private static ExecutorService singleService = Executors.newSingleThreadExecutor();
// -調劑型線程池
// -這個池子裡的線程可以按schedule順次delay履行,或周期履行
private static ExecutorService scheduledService = Executors.newScheduledThreadPool(10);
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Integer> customerList = new ArrayList<Integer>();
System.out.println(format.format(new Date()));
testFixedThreadPool(fixedService, customerList);
System.out.println("--------------------------");
testFixedThreadPool(fixedService, customerList);
fixedService.shutdown();
System.out.println(fixedService.isShutdown());
System.out.println("----------------------------------------------------");
testCacheThreadPool(cacheService, customerList);
System.out.println("----------------------------------------------------");
testCacheThreadPool(cacheService, customerList);
cacheService.shutdownNow();
System.out.println("----------------------------------------------------");
testSingleServiceThreadPool(singleService, customerList);
testSingleServiceThreadPool(singleService, customerList);
singleService.shutdown();
System.out.println("----------------------------------------------------");
testScheduledServiceThreadPool(scheduledService, customerList);
testScheduledServiceThreadPool(scheduledService, customerList);
scheduledService.shutdown();
}
public static void testScheduledServiceThreadPool(ExecutorService service, List<Integer> customerList) {
List<Callable<Integer>> listCallable = new ArrayList<Callable<Integer>>();
for (int i = 0; i < 10; i++) {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return new Random().nextInt(10);
}
};
listCallable.add(callable);
}
try {
List<Future<Integer>> listFuture = service.invokeAll(listCallable);
for (Future<Integer> future : listFuture) {
Integer id = future.get();
customerList.add(id);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(customerList.toString());
}
public static void testSingleServiceThreadPool(ExecutorService service, List<Integer> customerList) {
List<Callable<List<Integer>>> listCallable = new ArrayList<Callable<List<Integer>>>();
for (int i = 0; i < 10; i++) {
Callable<List<Integer>> callable = new Callable<List<Integer>>() {
@Override
public List<Integer> call() throws Exception {
List<Integer> list = getList(new Random().nextInt(10));
boolean isStop = false;
while (list.size() > 0 && !isStop) {
System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
isStop = true;
}
return list;
}
};
listCallable.add(callable);
}
try {
List<Future<List<Integer>>> listFuture = service.invokeAll(listCallable);
for (Future<List<Integer>> future : listFuture) {
List<Integer> list = future.get();
customerList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(customerList.toString());
}
public static void testCacheThreadPool(ExecutorService service, List<Integer> customerList) {
List<Callable<List<Integer>>> listCallable = new ArrayList<Callable<List<Integer>>>();
for (int i = 0; i < 10; i++) {
Callable<List<Integer>> callable = new Callable<List<Integer>>() {
@Override
public List<Integer> call() throws Exception {
List<Integer> list = getList(new Random().nextInt(10));
boolean isStop = false;
while (list.size() > 0 && !isStop) {
System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
isStop = true;
}
return list;
}
};
listCallable.add(callable);
}
try {
List<Future<List<Integer>>> listFuture = service.invokeAll(listCallable);
for (Future<List<Integer>> future : listFuture) {
List<Integer> list = future.get();
customerList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(customerList.toString());
}
public static void testFixedThreadPool(ExecutorService service, List<Integer> customerList) {
List<Callable<List<Integer>>> listCallable = new ArrayList<Callable<List<Integer>>>();
for (int i = 0; i < 10; i++) {
Callable<List<Integer>> callable = new Callable<List<Integer>>() {
@Override
public List<Integer> call() throws Exception {
List<Integer> list = getList(new Random().nextInt(10));
boolean isStop = false;
while (list.size() > 0 && !isStop) {
System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
isStop = true;
}
return list;
}
};
listCallable.add(callable);
}
try {
List<Future<List<Integer>>> listFuture = service.invokeAll(listCallable);
for (Future<List<Integer>> future : listFuture) {
List<Integer> list = future.get();
customerList.addAll(list);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(customerList.toString());
}
public static List<Integer> getList(int x) {
List<Integer> list = new ArrayList<Integer>();
list.add(x);
list.add(x * x);
return list;
}
}
應用:LinkedBlockingQueue完成線程池講授
//例如:corePoolSize=3,maximumPoolSize=6,LinkedBlockingQueue(10) //RejectedExecutionHandler默許處置方法是:ThreadPoolExecutor.AbortPolicy //ThreadPoolExecutor executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10)); //1.假如線程池中(也就是挪用executorService.execute)運轉的線程未到達LinkedBlockingQueue.init(10)的話,以後履行的線程數是:corePoolSize(3) //2.假如跨越了LinkedBlockingQueue.init(10)而且跨越的數>=init(10)+corePoolSize(3)的話,而且小於init(10)+maximumPoolSize. 以後啟動的線程數是:(以後線程數-init(10)) //3.假如挪用的線程數跨越了init(10)+maximumPoolSize 則依據RejectedExecutionHandler的規矩處置。
關於:RejectedExecutionHandler幾種默許完成講授
//默許應用:ThreadPoolExecutor.AbortPolicy,處置法式遭到謝絕將拋出運轉時RejectedExecutionException。 RejectedExecutionHandler policy=new ThreadPoolExecutor.AbortPolicy(); // //在 ThreadPoolExecutor.CallerRunsPolicy 中,線程挪用運轉該義務的execute自己。此戰略供給簡略的反應掌握機制,可以或許減緩新義務的提交速度。 // policy=new ThreadPoolExecutor.CallerRunsPolicy(); // //在 ThreadPoolExecutor.DiscardPolicy 中,不克不及履行的義務將被刪除。 // policy=new ThreadPoolExecutor.DiscardPolicy(); // //在 ThreadPoolExecutor.DiscardOldestPolicy 中,假如履行法式還沒有封閉,則位於任務隊列頭部的義務將被刪除,然後重試履行法式(假如再次掉敗,則反復此進程)。 // policy=new ThreadPoolExecutor.DiscardOldestPolicy();
以上這篇Java線程池的幾種完成辦法和差別引見就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。