-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.java
More file actions
57 lines (51 loc) · 1.9 KB
/
ThreadPool.java
File metadata and controls
57 lines (51 loc) · 1.9 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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class ThreadPool {
private BlockingQueue<Task> taskBlockingQueue;
private List<WorkerThread> workerThreadList;
private final int numberOfThreads;
public ThreadPool(int numberOfThreads) {
this.numberOfThreads = numberOfThreads;
taskBlockingQueue = new LinkedBlockingDeque<>();
workerThreadList = new ArrayList<>(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
WorkerThread workerThread = new WorkerThread();
workerThreadList.add(workerThread);
workerThread.start();
}
}
public void execute(Task task) {
synchronized (taskBlockingQueue) {
taskBlockingQueue.add(task);
taskBlockingQueue.notify();
}
}
public class WorkerThread extends Thread {
@Override
public void run() {
super.run();
Runnable task;
while (true) {
synchronized (taskBlockingQueue) {
while (taskBlockingQueue.isEmpty()) {
try {
taskBlockingQueue.wait();
} catch (InterruptedException e) {
System.out.println("An error occurred while queue is waiting: " + e.getMessage());
e.printStackTrace();
}
}
task = taskBlockingQueue.poll();
try {
task.run();
} catch (RuntimeException e) {
System.out.println("This thread pool is interrupted due to an issue: " + e.getMessage());
e.printStackTrace();
}
}
}
}
}
}