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

JAVA并发,线程工厂及自定义线程池

时间:2015-04-22 01:50:08      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.xt.thinks21_2;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.SynchronousQueue;
 6 import java.util.concurrent.ThreadFactory;
 7 import java.util.concurrent.ThreadPoolExecutor;
 8 import java.util.concurrent.TimeUnit;
 9 
10 /**
11  * 后台线程工厂测试
12  * 
13  * @step 1
14  * @author Administrator
15  *
16  */
17 class DaemonThreadFactory implements ThreadFactory {
18 
19     @Override
20     public Thread newThread(Runnable r) {
21         // TODO Auto-generated method stub
22         Thread t = new Thread(r);
23         t.setDaemon(true);
24         return t;
25     }
26 
27 }
28 
29 /**
30  * 自定义线程池执行器
31  * 
32  * @step 5
33  * @author Administrator
34  *
35  */
36 class DaemonThreadPoolExecutor extends ThreadPoolExecutor {
37 
38     public DaemonThreadPoolExecutor() {
39         super(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
40                 new SynchronousQueue<Runnable>(), new DaemonThreadFactory());
41         // TODO Auto-generated constructor stub
42     }
43 
44 }
45 
46 /**
47  * 后台线程测试
48  * 
49  * @step 2
50  * @author Administrator
51  *
52  */
53 public class DaemonFromFactory implements Runnable {
54     // @step 3
55     @Override
56     public void run() {
57         // TODO Auto-generated method stub
58         while (true) {
59             try {
60                 TimeUnit.MILLISECONDS.sleep(100);
61                 System.out.println(Thread.currentThread() + ":" + this);
62             } catch (InterruptedException e) {
63                 // TODO Auto-generated catch block
64                 e.printStackTrace();
65             }
66         }
67     }
68 
69     public static void main(String[] args) {
70         // @step 4
71         ExecutorService es = Executors
72                 .newCachedThreadPool(new DaemonThreadFactory());
73         for (int i = 0; i < 10; i++) {
74             es.execute(new DaemonFromFactory());// 执行后台线程
75         }
76         es.shutdown();
77         // @step 6
78         // 自定义的线程池执行器
79         DaemonThreadPoolExecutor dte = new DaemonThreadPoolExecutor();
80         for (int i = 0; i < 10; i++) {
81             dte.execute(new DaemonFromFactory());// 执行后台线程
82         }
83         dte.shutdown();
84         System.out.println("ALL DEAMON THREAD IS START!");
85         try {
86             TimeUnit.MILLISECONDS.sleep(125);
87         } catch (InterruptedException e) {
88             // TODO Auto-generated catch block
89             e.printStackTrace();
90         }
91     }
92 }

通过编写定制的ThreadFactory可以定制游Executor创建的线程的属性(后台、优先级、名称)

 

JAVA并发,线程工厂及自定义线程池

标签:

原文地址:http://www.cnblogs.com/wubingshenyin/p/4446062.html

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