線程池ExecutorService和ThreadPoolExecutor
ExecutorService返回的線程池對象的弊端如下:1)FixedThreadPool和SingleThreadPool:允許的請求隊列長度爲Integer.MAX_VALUE,可能會堆積大量的請求,從而導致OOM。2)CachedThreadPool和ScheduledThreadPool:允許的創建線程數量爲Integer.MAX_VALUE,可能會創建大量的線程,從而導致OOM
1.線程方法類
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "(自定義)正在執行。。。");
for (int i = 0; i < 10; i++) {
//Timer timer = new Timer();
System.out.println(Thread.currentThread().getName()+"=="+i);
}
}
}
2.線程池ExecutorService和ThreadPoolExecutor測試類
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*
* @author zouyang
* (推薦使用)
* 創建一個可緩存的線程池。如果線程池的大小超過了處理任務所需要的線程,
* 那麼就會回收部分空閒(60秒不執行任務)的線程
*
*/
public class TestCachedThreadPool {
public static void main(String[] args) {
//ExecutorService測試方法
//創建一個可重用固定線程數的線程池
ExecutorService pool = Executors.newCachedThreadPool();
//創建一個可重用固定線程數的線程池
//ExecutorService pool = Executors.newFixedThreadPool(1);//指定個數
//創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口
/* Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
Thread t4 = new MyThread();
Thread t5 = new MyThread();
//將線程放入池中進行執行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
*/
for (int i = 0; i < 5; i++) {
//Thread t1 = new MyThread();
//pool.execute(t1);
}
pool.shutdown();//關閉線程池
//ThreadPoolExecutor測試方法
System.out.println("ThreadPoolExecutor線程池");
ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 10, 10, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10));
for (int i = 0; i < 5; i++) {
Thread t1 = new MyThread();
tpe.execute(t1);
}
tpe.shutdown();//關閉線程池
}
}