线程池的使用

1.基本方法

1.固定大小的线程池

ExecutorService threadPool = Executors.newFixedThreadPool(int nThreads)

 

2.缓存线程池

ExecutorService threadPool = Executors.newCachedThreadPool()

根据需要创建一个新的线程池,当之前构造的线程可用时会重用之前的线程

 

3.单一线程池

ExecutorService threadPool = Executors.newSingleThreadExecutor()

思考:

如果要实现线程死掉之后重新启动的功能, 使用单一线程池是否可行?

答: 应该是可行的, 因为线程总是在不断地被创建

 

4.线程池的调度(schedule)

示例代码:

1         //用线程池启动定时器,10s之后运行Runnable
2         Executors.newScheduledThreadPool(3).schedule(new Runnable(){
3                 @Override
4                 public void run() {
5                     System.out.println("shen_smile");
6                 }
7             }, 10, TimeUnit.SECONDS);

 

2.全部测试代码本例中, 所有task完成之后会启动定时器, 过5s后会输出shen_smile

 1 public class Test {
 2     public static void main(String[] args) {
 3         //单一线程池
 4         ExecutorService threadPool = Executors.newSingleThreadExecutor();
 5         for(int i=1;i<6;i++){
 6             final int task = i;
 7             threadPool.execute(new Runnable(){
 8                 @Override
 9                 public void run() {
10                     for(int j=1;j<10;j++){
11                         try {
12                             Thread.sleep(20);
13                         } catch (InterruptedException e) {
14                             // TODO Auto-generated catch block
15                             e.printStackTrace();
16                         }
17                         System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
18                     }
19                 }
20             });
21         }
22         System.out.println("all of 10 tasks have committed! ");
23         threadPool.shutdown();
24         //用线程池启动定时器,10s之后运行Runnable
25         Executors.newScheduledThreadPool(3).schedule(new Runnable(){
26                 @Override
27                 public void run() {
28                     System.out.println("shen_smile");
29                 }
30             }, 10, TimeUnit.SECONDS);
31     }
32 }

 

posted on 2016-01-17 20:24  沈小洋  阅读(177)  评论(0编辑  收藏  举报

导航