Java線程池的幾種實現方法和區別介紹_java

來源:互聯網
上載者:User

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線程池的幾種實現方法和區別介紹就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.