码迷,mamicode.com
首页 > 编程语言 > 详细

多线程 线程池

时间:2015-06-25 00:03:55      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

多线程 线程池

标签:

原文地址:http://www.cnblogs.com/sherrykid/p/4598898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!