-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
ThreadManager.java
87 lines (79 loc) · 2.15 KB
/
ThreadManager.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
package me.nallar.tickthreading.minecraft;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import me.nallar.tickthreading.Log;
public class ThreadManager {
private final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
private final Set<Thread> workThreads = new HashSet<Thread>();
private final Object readyLock = new Object();
private final AtomicInteger completed = new AtomicInteger(0);
public ThreadManager(int threads, String name) {
for (int i = 0; i < threads; i++) {
Thread workThread = new WorkThread();
workThread.setName(name + " - " + (i + 1));
workThread.setDaemon(true);
workThread.start();
workThreads.add(workThread);
}
}
public void run(Collection<? extends Runnable> tasks) {
completed.addAndGet(-tasks.size());
taskQueue.addAll(tasks);
while (completed.get() < 0) {
try {
synchronized (readyLock) {
readyLock.wait(0, 100);
}
} catch (InterruptedException ignored) {
}
}
}
public void runBackground(Runnable runnable) {
completed.decrementAndGet();
taskQueue.add(runnable);
}
public void stop() {
for (Thread thread : workThreads) {
taskQueue.add(null);
}
try {
Thread.sleep(50);
} catch (InterruptedException ignored) {
}
for (Thread thread : workThreads) {
thread.stop();
}
workThreads.clear();
}
private class WorkThread extends Thread {
@Override
public void run() {
while (true) {
try {
Runnable runnable;
synchronized (taskQueue) {
runnable = taskQueue.take();
}
if (runnable == null) {
return;
}
runnable.run();
} catch (InterruptedException ignored) {
} catch (ThreadDeath rethrown) {
throw rethrown;
} catch (Exception e) {
Log.severe("Unhandled exception in worker thread", e);
}
if (completed.incrementAndGet() == 0) {
synchronized (readyLock) {
readyLock.notify();
}
}
}
}
}
}