背景:
阅读新闻
简单多线程服务器实现
[日期:2010-01-15] 来源:Linux社区 作者:HSD编辑 [字体:]
这个Server调用的是自己实现的一个基于任务队列的简单线程池:
1 package testmutithreadserver.old.threadpool;
2
3 import java.util.LinkedList;
4
5 /**
6 * 简单线程池 (基于工作队列的同步线程池)
7 *
8 * @author zhangjun
9 *
10 */
11 public class ThreadPool extends ThreadGroup {
12 private final static String THREADPOOL = "thread pool";
13 private final static String WORKTHREAD = "work thread ";
14 private final static int DEFAULTSIZE = Runtime.getRuntime()
15 .availableProcessors() + 1;
16 private LinkedList<Runnable> taskQueue;
17 private boolean isPoolClose = false;
18
19 public ThreadPool() {
20 this(DEFAULTSIZE);
21 }
22
23 public ThreadPool(int size) {
24 super(THREADPOOL);
25 setDaemon(true);
26 taskQueue = new LinkedList<Runnable>();
27 initWorkThread(size);
28 }
29
30 private void initWorkThread(int size) {
31 for (int i = 0; i < size; i++) {
32 new WorkThread(WORKTHREAD + i).start();
33 }
34 try {
35 Thread.sleep(100 * size);
36 } catch (InterruptedException e) {
37 }
38 }
39
40 public synchronized void execute(Runnable task) {
41 if (isPoolClose) {
42 throw new IllegalStateException();
43 }
44 if (task != null) {
45 taskQueue.add(task);
46 notify();
47 }
48 }
49
50 private synchronized Runnable getTask() throws InterruptedException {
51 if (taskQueue.size() == 0) {
52 if (isPoolClose) {
53 return null;
54 }
55 wait();
56 }
57 if (taskQueue.size() == 0) {
58 return null;
59 }
60 return taskQueue.removeFirst();
61 }
62
63 public void shutdown() {
64 waitFinish();
65 synchronized (this) {
66 isPoolClose = true;
67 interrupt();
68 taskQueue.clear();
69 }
70 }
71
72 private void waitFinish() {
73 synchronized (this) {
74 isPoolClose = true;
75 notifyAll();
76 }
77 Thread[] threads = new Thread[activeCount()];
78 enumerate(threads);
79 try {
80 for (Thread t : threads) {
81 t.join();
82 }
83 } catch (InterruptedException e) {
84 //swallow this
85 }
86 }
87
88 private class WorkThread extends Thread {
89
90 public WorkThread(String name) {
91 super(ThreadPool.this, name);
92 }
93
94 @Override
95 public void run() {
96 while (!isInterrupted()) {
97 Runnable task = null;
98 try {
99 task = getTask();
100 } catch (InterruptedException e) {
101 //swallow this
102 }
103 if (task == null) {
104 return;
105 }
106 try {
107 task.run();
108 } catch (Throwable e) {
109 e.printStackTrace();
110 }
111 }
112 }
113
114 }
115 }
116
相关资讯 服务器
本文评论 查看全部评论 (0)
尊重网上道德,遵守中华人民共和国的各项有关法律法规 承担一切因您的行为而直接或间接导致的民事或刑事法律责任 本站管理人员有权保留或删除其管辖留言中的任意内容 本站有权在网站内转载或引用您的评论 参与本评论即表明您已经阅读并接受上述条款
评论声明
最新资讯