|
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 線程池例子
*
* @author Msquirrel
*
*/
public class TestThreadPoolExecutor {
public static void main(String arg[]) {
// BlockingQueue<Runnable> bq = new LinkedBlockingQueue<Runnable>();
// ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 1,
// TimeUnit.DAYS,bq);
/**
* 第一參數:指的是保留的線程池大小。
* 第二參數:指的是線程池的最大大小。
* 第三參數:線程池維護線程所允許的空閑時間。
* 第四參數: 線程池維護線程所允許的空閑時間的單位。
* 第五參數: 表示存放任務的隊列。
* 第六參數: 線程池對拒絕任務的處理策略,預設值ThreadPoolExecutor.AbortPolicy()。
*/
ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 1, TimeUnit.DAYS,
new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardOldestPolicy());
/**
* 迴圈加線程
*/
for (int i = 0; i < 20; i++) {
// 把線程加到線程容器裡
tpe.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
// 睡眠1秒鐘
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(String.format("thread %d finished",
this.hashCode()));
}
});
}
/**
* 調用shutdown() 方法之後,主線程就馬上結束了,而線程池會繼續運行直到所有任務執行完才會停止。如果不調用 shutdown()
* 方法,那麼線程池會一直保持下去,以便隨時添加新的任務。(shutdown() 方法不會阻塞)
*/
tpe.shutdown();
}
} |