-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.java
More file actions
107 lines (104 loc) · 2.55 KB
/
Copy pathThreadPool.java
File metadata and controls
107 lines (104 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.List;
import java.util.LinkedList;
public final class ThreadPool {
private static ThreadPool pool=null;
private static int pool_size=5;
private volatile int finish_size=0;
private WorkThread[] workThread;
private List<Runnable> taskQueue;
private ThreadPool(){
this(pool_size);
}
private ThreadPool(int pool_size){
this.pool_size=pool_size;
taskQueue=new LinkedList<Runnable>();
workThread=new WorkThread[pool_size];
for(int i=0;i<pool_size;i++){
workThread[i]=new WorkThread();
workThread[i].start();
}
}
public static ThreadPool createThreadPool(){
return createThreadPool(ThreadPool.pool_size);
}
public static ThreadPool createThreadPool(int pool_size){
if(pool_size<=0)
pool_size=ThreadPool.pool_size;
if(pool==null)
pool=new ThreadPool(pool_size);
return pool;
}
public void execute(Runnable task){
synchronized(taskQueue){
taskQueue.add(task);
taskQueue.notify();
}
}
public void execute(Runnable[] tasks){
synchronized(taskQueue){
for(Runnable task : tasks){
taskQueue.add(task);
}
taskQueue.notify();
}
}
public int getThreadPoolSize(){
return pool_size;
}
public int getFinishedThreadSize(){
return finish_size;
}
public int getWaitingThreadSize(){
return taskQueue.size();
}
public void destroy(){
while(!taskQueue.isEmpty()){
try{
Thread.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int i=0;i<pool_size;i++){
workThread[i].stopRunning();
workThread[i]=null;
}
pool=null;
taskQueue.clear();
}
@Override
public String toString(){
return"ThreadPool Info:\nthread pool size: "+pool_size+"\nfinished thread num: "+getFinishedThreadSize()+"\nwaiting thread num: "+getWaitingThreadSize();
}
private class WorkThread extends Thread{
private boolean isRunning=true;
@Override
public void run(){
Runnable task=null;
while(isRunning){
synchronized(taskQueue){
while(isRunning&&taskQueue.isEmpty()){
try{
taskQueue.wait(20);
}catch(InterruptedException e){
e.printStackTrace();
}
}
if(!taskQueue.isEmpty())
task=taskQueue.remove(0);
}
if(task!=null){
task.run();
}
addFinishedThreadSize();
task=null;
}
}
private synchronized void addFinishedThreadSize(){
finish_size++;
}
public void stopRunning(){
isRunning=false;
}
}
}