首页 > 代码库 > 线程池

线程池

 1 package concurrentStudy;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 public class ThreadPoolImpl1 {
 7     public static void main(String[] args) {
 8         ExecutorService ec = Executors.newFixedThreadPool(4);
 9         for(int i=0;i<10;i++){
10             ec.execute(new WorkerThread("start"+i));//提交10次任务立即执行完
11         }    
12         System.out.println("任务提交完毕");
13         ec.shutdown();    //拒绝接受新任务,尝试关闭线程,不会影响正在执行的线程,不取消等待队列中的任务
14         System.out.println("尝试关闭线程已开启");
15         while(!ec.isTerminated()){    //等待所有任务执行完毕(包括正在执行和已经提交的)
16             
17         }
18         System.out.println("all threads finished");
19     }
20 }
21 class WorkerThread implements Runnable{
22     private String command;
23     
24     
25     public WorkerThread(String command) {
26         super();
27         this.command = command;
28     }
29 
30 
31     @Override
32     public void run() {
33         System.out.println(Thread.currentThread().getName()+"Start.command="+command);
34         try {
35             Thread.sleep(5000);
36         } catch (InterruptedException e) {
37             // TODO Auto-generated catch block
38             e.printStackTrace();
39         }
40         System.out.println(Thread.currentThread().getName()+"end");
41     }
42     
43 }

1.固定线程池,上例中最大只有4个线程提供服务,对应的是无界队列。

2.Runnable与Callback均是任务接口,但Runnable无返回值,不可抛出可检查异常

结果:

 1 pool-1-thread-1Start.command=start0
 2 pool-1-thread-3Start.command=start2
 3 pool-1-thread-2Start.command=start1
 4 pool-1-thread-4Start.command=start3
 5 任务提交完毕
 6 尝试关闭线程已开启
 7 pool-1-thread-1end
 8 pool-1-thread-2end
 9 pool-1-thread-2Start.command=start5
10 pool-1-thread-4end
11 pool-1-thread-3end
12 pool-1-thread-3Start.command=start7
13 pool-1-thread-4Start.command=start6
14 pool-1-thread-1Start.command=start4
15 pool-1-thread-1end
16 pool-1-thread-2end
17 pool-1-thread-3end
18 pool-1-thread-4end
19 pool-1-thread-2Start.command=start9
20 pool-1-thread-1Start.command=start8
21 pool-1-thread-1end
22 pool-1-thread-2end
23 all threads finished

 

a