package cn.itcast.heima2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
//固定的线程池
//可以往线程池放n个任务,但每次执行只执行3个任务,别的任务在排队
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
//缓存的线程池,有几个任务几个线程,动态变化
//ExecutorService threadPool = Executors.newCachedThreadPool();
//线程池
//单线程,线程池只有一个线程
ExecutorService 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=1;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 tasks have committed! ");
//threadPool.shutdown();池子中没有任务关闭线程,所有任务都执行完
//threadPool.shutdownNow();还有任务没有执行完,都关闭线程
//线程池多久之间后执行任务 (任务,时间,频率)
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
}
}, 10, TimeUnit.SECONDS);
//多久频率后执行
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(//固定频率
new Runnable(){
@Override
public void run() {
System.out.println("bombing!");
}},
6,
2,//每个2秒
TimeUnit.SECONDS);
}
}