-
Notifications
You must be signed in to change notification settings - Fork 4
/
CustomThreadPool.java
106 lines (90 loc) · 1.98 KB
/
CustomThreadPool.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.soni.threadPool;
import java.util.LinkedList;
import java.util.Queue;
public class CustomThreadPool {
public static void main(String[] args) {
TheadPoolManager pool = new TheadPoolManager(2);
pool.submitTask(()->{
System.out.println("Executing task 1");
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finished task 1");
});
pool.submitTask(()->{
System.out.println("Executing task 2");
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finished task 2");
});
pool.submitTask(()->{
System.out.println("Executing task 3");
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finished task 3");
});
}
}
class TheadPoolManager {
private CustomQueue<Runnable> queue;
public TheadPoolManager(int nThreads) {
queue = new CustomQueue<Runnable>(nThreads);
for(int i=0; i<nThreads; i++) {
Thread t = new Thread(new ExecutionThread(queue));
t.setName("Thread-"+(i+1));
t.start();
}
}
public void submitTask(Runnable runnable) {
queue.enqueue(runnable);
}
}
class ExecutionThread implements Runnable {
private CustomQueue<Runnable> queue;
public ExecutionThread(CustomQueue<Runnable> queue) {
this.queue = queue;
}
public void run() {
while(true) {
queue.dequeue().run();
}
}
}
class CustomQueue<T> {
private Queue<T> queue;
private int capacity;
public CustomQueue(int capacity) {
this.queue = new LinkedList<T>();
this.capacity = capacity;
}
public synchronized void enqueue(T elt) {
if(queue.size()==capacity) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(elt);
notifyAll();
}
public synchronized T dequeue() {
if(queue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notifyAll();
return queue.poll();
}
}