以實例簡介Java中線程池的任務特色。本站提示廣大學習愛好者:(以實例簡介Java中線程池的任務特色)文章只能為提供參考,不一定能成為您想要的結果。以下是以實例簡介Java中線程池的任務特色正文
甚麼緣由使我們不能不應用線程池?
小我以為重要緣由是:短時光內須要處置的義務數目許多
應用線程池的利益:
1.削減在創立和燒毀線程上所花的時光和體系資本的開支
2.如不應用線程池,有能夠形成體系創立年夜量線程而招致消費完體系內存
以下是Java自帶的幾種線程池:
1、newFixedThreadPool 創立一個指定任務線程數目的線程池。
每當提交一個義務就創立一個任務線程,假如任務線程數目到達線程池初始的最年夜數,則將提交的義務存入到池隊列中。
2、newCachedThreadPool 創立一個可緩存的線程池。
這類類型的線程池特色是:
1).任務線程的創立數目簡直沒無限制(其實也無限制的,數量為Interger. MAX_VALUE), 如許可靈巧的往線程池中添加線程。
2).假如長時光沒有往線程池中提交義務,即假如任務線程余暇了指定的時光(默許為1分鐘),則該任務線程將主動終止。終止後,假如你又提交了新的義務,則線程池從新創立一個任務線程。
3、newSingleThreadExecutor 創立一個單線程化的Executor,即只創立獨一的任務者線程來履行義務,假如這個線程異常停止,會有另外一個代替它,包管次序履行(我認為這點是它的特點)。
單任務線程最年夜的特色是可包管次序地履行各個義務,而且在隨意率性給定的時光不會有多個線程是運動的 。
4、newScheduleThreadPool 創立一個定長的線程池,並且支撐准時的和周期性的義務履行,相似於Timer。
總結:
一.FixedThreadPool是一個典范且優良的線程池,它具有線程池進步法式效力和節儉創立線程時所耗的開支的長處。但在線程池余暇時,即線程池中沒有可運轉義務時,它不會釋下班作線程,還會占用必定的體系資本。
二.CachedThreadPool的特色就是在線程池余暇時,即線程池中沒有可運轉義務時,它會釋下班作線程,從而釋下班作線程所占用的資本。然則,但當湧現新義務時,又要創立一新的任務線程,又要必定的體系開支。而且,在應用CachedThreadPool時,必定要留意掌握義務的數目,不然,因為年夜量線程同時運轉,很有會形成體系癱瘓。
Java線程池 ThreadPoolExecutor應用實例
package com.sondon.mayi.jpool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class JPoolLearn {
private static int produceTaskSleepTime = 3;
private static int produceTaskMaxNumber = 20;
public void testThreadPoolExecutor(){
/*
* ThreadPoolExecutor(
* int corePoolSize, //線程池保護線程的起碼數目
* int maximumPoolSize, //線程池保護線程的最年夜數目
* long keepAliveTime, //線程池保護線程所許可的余暇時光
* TimeUnit unit, //線程池保護線程所許可的余暇時光的單元
* BlockingQueue<Runnable> workQueue, //線程池所應用的緩沖隊列
* RejectedExecutionHandler handler //線程池對謝絕義務的處置戰略 )
*/
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
5,
10,
3,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
for (int i = 1; i <= produceTaskMaxNumber; i++) {
try {
// 發生一個義務,並將其參加到線程池
String task = "task---" + i;
threadPool.execute(new ThreadPoolTask(task));
System.out.println("activeCount :"+ threadPool.getActiveCount());
// 便於不雅察,期待一段時光
Thread.sleep(produceTaskSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
}
//檢查以後的線程池狀態
while(true){
try {
Thread.sleep(3000);
System.out.println("pool size :"+threadPool.getPoolSize());//線程池中線程數目
System.out.println("active count :"+threadPool.getActiveCount());//線程池中運動的線程數目
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
*
* @Author 蔡文鋒
* @Data_Time 2015年7月25日 下晝4:06:28
* @Description { 測試分歧線程池形式 }
*/
public void testNewCachedThreadPool(){
ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newCachedThreadPool();
// ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newFixedThreadPool(100);
// ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newScheduledThreadPool(100);
// ThreadPoolExecutor threadPool=(ThreadPoolExecutor) Executors.newSingleThreadExecutor();
try {
for (int i = 0; i < 100; i++) {
// 發生一個義務,並將其參加到線程池
String task = "task---" + i;
threadPool.execute(new ThreadPoolTask(task));
System.out.println("activeCount :");
// 便於不雅察,期待一段時光
Thread.sleep(produceTaskSleepTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//檢查以後的線程池狀態
while(true){
try {
Thread.sleep(3000);
System.out.println("pool size :"+threadPool.getPoolSize());//線程池中線程數目
System.out.println("active count :"+threadPool.getActiveCount());//線程池中運動的線程數目
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
*
* @Author 蔡文鋒
* @Data_Time 2015年7月25日 下晝4:06:58
* @Description { 測試callable與runable辦法的差別 }
*/
public void testNewCachedThreadPool_callable(){
ExecutorService es=Executors.newFixedThreadPool(10);
try {
// String result=es.submit(new MyCallable<String>()).get();
// System.out.println("callable result :"+result);
String result=(String) es.submit(new ThreadPoolTask("")).get();
System.out.println("runable result :"+result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JPoolLearn().testNewCachedThreadPool();
}
}
/**
* 線程池履行的義務
*/
class ThreadPoolTask implements Runnable {
private static int consumeTaskSleepTime = 2000;
// 保留義務所須要的數據
private Object threadPoolTaskData;
ThreadPoolTask(Object tasks) {
this.threadPoolTaskData = tasks;
}
public void run() {
System.out.println("start .." + threadPoolTaskData);
try {
// Sleep 2秒 模仿耗時操作
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
threadPoolTaskData = null;
}
public Object getTask() {
return this.threadPoolTaskData;
}
}
/**
*
* @Project : JPool
* @Package : com.sondon.mayi.jpool
* @Class : MyCallable
* @param <T>
*/
class MyCallable<T> implements Callable<T>{
@Override
public T call() throws Exception {
System.out.println("開端履行Callable");
return (T) "測試callable接口";
}
}