-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunOnThreadN.java
executable file
·119 lines (100 loc) · 2.1 KB
/
RunOnThreadN.java
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
108
109
110
111
112
113
114
115
116
117
118
119
package f12;
import java.util.LinkedList;
public class RunOnThreadN {
private Buffer<Runnable> buffer = new Buffer<Runnable>();
private LinkedList<Worker> workers;
private int n;
public RunOnThreadN(int n) {
this.n = n;
}
public void start() {
Worker worker;
if(workers==null) {
workers = new LinkedList<Worker>();
for(int i=0; i<n; i++) {
worker = new Worker();
worker.start();
workers.add(worker);
}
}
}
public synchronized void execute(Runnable runnable) {
buffer.put(runnable);
}
public synchronized void stop() {
// if(workers!=null) {
// buffer.clear();
// for(Worker worker : workers) {
// worker.interrupt();
// }
// workers = null;
// }
if(workers!=null) {
for(int i=0; i<n; i++) {
execute(new StopWorker());
}
workers.clear();
workers = null;
}
}
private class StopWorker implements Runnable {
public void run() {
Thread.currentThread().interrupt();
}
public String toString() {
return Thread.currentThread() + " StopWorker";
}
}
private class Worker extends Thread {
public void run() {
while(!Thread.interrupted()) {
try {
buffer.get().run();
} catch(InterruptedException e) {
System.out.println(e);
break;
}
}
}
}
private class Buffer<T> {
private LinkedList<T> buffer = new LinkedList<T>();
public synchronized void put(T obj) {
buffer.addLast(obj);
notifyAll();
}
public synchronized T get() throws InterruptedException {
while(buffer.isEmpty()) {
wait();
}
return buffer.removeFirst();
}
public synchronized void clear() {
buffer.clear();
}
public int size() {
return buffer.size();
}
}
public static void main(String[] args) {
RunOnThreadN pool = new RunOnThreadN(20);
pool.start();
for(int i=0; i<100; i++) {
pool.execute(new Task(i));
}
// pool.start();
pool.stop();
}
}
class Task implements Runnable {
private int a;
public Task(int a) {
this.a = a;
}
public void run() {
System.out.println(Thread.currentThread() + ": " + a);
}
public String toString() {
return ""+a;
}
}