Excutors的应用
1.创建固定大小的线程池
2.创建缓存线程池
3.创建单一线程池
关闭线程池
shutdown和shutDownNow的区别
用线程池启动定时器
调用ScheduledExecutorService的schedule方法,返回的ScheduleFuture对象可以取消任务
支持间隔重复任务的定时方式,不直接支持绝对定时方式,需要转换为相对时间
eg:
package com.qunar.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(3); //创建一个固定大小的线程池
//ExecutorService threadPool = Executors.newCachedThreadPool();//缓存线程池,内部线程个数不确定
ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程池,至少保证有一个线程(实现线程死了重新启动)
for (int i = 0; i < 10; i++) {
final int taskId = i;
threadPool.execute(new Runnable() {//往里面扔任务
@Override
public void run() {
for (int j = 0; j < 10; j++) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()
.getName() + " is looping of " + j+" for task of"+taskId);
}
}
});
}
/*System.out.println("all task had commited!");
threadPool.shutdownNow();*/
//固定频率的咋三秒后开始爆炸,然后每隔两秒爆炸一次
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing");
}
},3,2,TimeUnit.SECONDS);
}
}