多线程 线程池 ExecutorService

 1 package org.zln.thread;
 2 
 3 import java.util.Date;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 
 7 /**
 8  * Created by sherry on 000024/6/24 22:50.
 9  */
10 public class TestExecutorService implements Runnable{
11     public static void main(String[] args) {
12         new Thread(new TestExecutorService()).start();
13         System.out.println(new Date()+"主线程结束");
14     }
15 
16     /*之所以将for循环写在一个run中,是为了防止线程池等待过程中造成的主线程堵塞*/
17     @Override
18     public void run() {
19         /*创建一个大小为3的线程池*/
20         ExecutorService executorService = Executors.newFixedThreadPool(3);
21         for (int i = 0; i < 20; i++) {
22             Runnable runnable = new Runnable() {
23                 @Override
24                 public void run() {
25                     long time = (long)(Math.random()*1000);
26                     System.out.println(new Date()+"休眠:"+time+" 毫秒");
27                     try {
28                         Thread.sleep(time);
29                     } catch (InterruptedException e) {
30                         e.printStackTrace();
31                     }
32                 }
33             };
34             /*启动一个线程*/
35             executorService.execute(runnable);
36         }
37         /*线程池必须使用shutdown显示关闭,否则当前线程无法退出*/
38         executorService.shutdown();
39     }
40 }

 

posted @ 2015-06-24 23:02  csnmd  阅读(396)  评论(0编辑  收藏  举报