/**
*
* @描述: 线程池 .
* @作者: Wnj .
* @创建时间: 2017年5月15日 .
* @版本: 1.0 .
*/
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
/**
* 固定的线程线:
*
* 每次只有3个任务被线程拿去服务,因为我只创建了3个线程,池子里有3个线程但可以有N个任务
* 这3个线程尽最大努力交替为这些任务服务,每次只有3个线程进行服务
*/
//ExecutorService threadPool = Executors.newFixedThreadPool(3);
/**
* 缓存的线程线:
* 任务来了,服务不过来的时候,自动增加新的线程,内部线程数不固定
*/
//ExecutorService threadPool = Executors.newCachedThreadPool();
/**
* 单线程线:
* 如果池子里的线程死了,会自动new出一个来
* 如果实现线程死掉后重新启动?这句话是错误的,死掉不会重新启动
*/
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) {
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.shutdownNow();
/**
* 定时器线程池
* 3个线程池任意一个去执行
*/
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing!");
}
}, 6, 2, TimeUnit.SECONDS);
}