线程池就是一个可以装线程的一个容器,线程池一般有三种
1固定线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);//开启线程池,固定的线程池
参数3 表示限制放入线程池的线程数
2缓存线程池
Executor threadPool = Executors.newCachedThreadPool();//开启缓存线程池,根据需要,自定添加线程
3单例线程池
Executor threadPool = Executors.newSingleThreadExecutor();//创建单一线程池,线程死掉后,会创建替补,即接班人,保证有一个线程。
线程池的启动方式如下
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is looping of "+j+"for task of"+ task);
}
});
一般是先往线程池里面添加任务后再执行。
线程池的关闭只有固定线程池才有此方法
threadPool.shutdown();//关闭线程池,只有线程运行完后关闭。
threadPool.shutdownNow();//关闭线程池不管没有完成
在此给出一个例子
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(3);//开启线程池,固定的线程池
// Executor threadPool = Executors.newCachedThreadPool();//开启缓存线程池,根据需要,自定添加线程
// Executor threadPool = Executors.newSingleThreadExecutor();//创建单一线程池,线程死掉后,会创建替补,即接班人,保证有一个线程。
for(int i=1;i<=10;i++){
final int task = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
for(int j=0;j<10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" is looping of "+j+"for task of"+ task);
}
}
});
}
System.out.println("all of 10 ttask have committed");
//下面两个方法只在固定线程池中有
// threadPool.shutdown();//关闭线程池,只有线程运行完后关闭。
// threadPool.shutdownNow();//关闭线程池不管没有完成
}
}
线程池还有定时器
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("bommbing");
}
}, 10,2,TimeUnit.SECONDS);//是指十秒炸一次,之后,每隔两秒炸一次
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("bommbing");
}
}, 10,TimeUnit.SECONDS);//每隔十秒炸一次