-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThreadPool.java
57 lines (48 loc) · 1.27 KB
/
ThreadPool.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
package threadPool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;
public class ThreadPool {
int nThread;
Worker[] workers;
LinkedBlockingQueue<Runnable> tasksQueue;
Logger logger = Logger.getLogger("ThreadPool");
public ThreadPool(int nThread) {
this.nThread = nThread;
workers = new Worker[nThread];
tasksQueue = new LinkedBlockingQueue<>();
for (int i = 0; i < nThread; i++) {
workers[i] = new Worker();
workers[i].start();
}
}
public void execute(Runnable task) {
synchronized (tasksQueue) {
tasksQueue.add(task);
tasksQueue.notifyAll();
}
}
private class Worker extends Thread {
Runnable task;
@Override
public void run() {
while (true) {
synchronized (tasksQueue) {
while (tasksQueue.isEmpty()) {
try {
tasksQueue.wait();
} catch (InterruptedException e) {
logger.info("thread pool is intruppted due to " + e.getMessage());
}
}
task = tasksQueue.poll();
}
try {
task.run();
} catch (RuntimeException re) {
logger.info("thread pool is intruppted due to " + re.getMessage());
System.out.println("thread pool is intruppted due to " + re.getMessage());
}
}
}
}
}