java 多线程 day09 线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by chengtao on 17/12/4.
*
*
* 线程池类:
* java.util.concurrent.Executors
* 常用的方法
* newFixedThreadPool(int nThreads) 创建线程数固定的线程池。
* newCachedThreadPool() 创建线程数不固定的线程池(缓存线程池,线程数随着任务数的变换而变化)。
* newSingleThreadExecutor(int nThreads) 创建单一线程池,唯一的线程死掉以后,会自动创建一个线程池。
* newScheduledThreadPool() 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
*/
public class Thread0901_ThreadPool {

public static void main(String[] args) {
//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(){
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(); 试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。
//threadPool.shutdown; 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。

Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
new Runnable(){
public void run() {
System.out.println("bombing!");

}},
6,
2,
TimeUnit.SECONDS);
}

}
posted @ 2017-12-04 00:49  为爱奋斗不息  阅读(152)  评论(0编辑  收藏  举报