/**
* 创建不同类型的线程池 Executors
*
* @author
*/
public class ThreadPoolTest01 {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(3); // 创建一个固定大小的线程池,5个线程
// ExecutorService threadPool = Executors.newCachedThreadPool(); //创建一个可变的线程池,线程个数自己控制
ExecutorService threadPool = Executors.newSingleThreadExecutor(); //线程池中只有一个线程,死掉后会有新的线程代替
for (int i = 1; i <= 10; i++) { //向线程池添加10个任务
final int taskId = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " loop of " + i + " task of " + taskId);
}
}
});
}
threadPool.shutdown(); //线程池中的线程都没有任务后关闭
// threadPool.shutdownNow(); //立刻关闭
}
}