-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyThreadPool.java
More file actions
63 lines (56 loc) · 1.68 KB
/
MyThreadPool.java
File metadata and controls
63 lines (56 loc) · 1.68 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
import java.util.ArrayList;
import java.util.LinkedList;
public class MyThreadPool {
private final int numberOfThreads;
private ArrayList<MyThread> threads;
private final LinkedList<Runnable> tasks;
public MyThreadPool(int numberOfThreads) {
this.numberOfThreads = numberOfThreads;
threads = new ArrayList<>(numberOfThreads);
tasks = new LinkedList<>();
for (int i = 0; i < numberOfThreads; ++i) {
threads.add(new MyThread());
threads.get(i).start();
}
}
public class MyThread extends Thread {
@Override
public void run() {
Runnable r;
while (true) {
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
r = tasks.removeFirst();
} try {
r.run();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
private void execute(Runnable r) {
synchronized (tasks) {
tasks.addLast(r);
tasks.notify();
}
}
public static class Task implements Runnable {
@Override
public void run() {
System.out.println("Executed.");
}
}
public static void main(String... args) {
MyThreadPool pool = new MyThreadPool(2);
for (int i = 0; i < 100; ++i) {
pool.execute(new Task());
}
}
}