-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.java
More file actions
90 lines (81 loc) · 2.02 KB
/
ThreadPool.java
File metadata and controls
90 lines (81 loc) · 2.02 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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadPool {
private int size = 4;
private boolean isLive = true;
private Queue<Runnable> tasks = new LinkedList<Runnable>();
private ArrayList<Thread> pool = new ArrayList<Thread>();
private final ReentrantLock lock = new ReentrantLock();
Condition notEmpty = lock.newCondition();
public ThreadPool() {
this.initiateThreadPool();
}
public ThreadPool(int size) {
this.size = size;
this.initiateThreadPool();
}
public void shutdown() {
lock.lock();
try {
isLive = false;
notEmpty.signalAll();
} finally {
lock.unlock();
}
pool.stream().forEach((w) -> w.interrupt());
pool.stream().forEach(w -> {
try {
w.join(5_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
});
}
private void initiateThreadPool() {
for (int i = 0; i < size; i++) {
String name = "thread-" + i;
Thread worker = new Thread(() -> {
while (true) {
Runnable task;
lock.lock();
try {
while (tasks.isEmpty()) {
if (!isLive)
return;
notEmpty.await();
}
task = tasks.poll();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
log("EXECUTED by: " + name);
task.run();
}
}, name);
pool.add(worker);
worker.start();
}
log("Created ThreadPool with " + size + " workers");
}
private void log(final String str) {
System.out.println(str);
}
public void execute(Runnable task) {
lock.lock();
try {
if (isLive) {
tasks.add(task);
}
} finally {
notEmpty.signal();
lock.unlock();
}
}
}