public class Test {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(2);
for(int i=0;i<2;i++) {
Task task = new Task(i);
threadPool.execute(task);
}
System.out.println("done");
}
}
public class Task implements Runnable{
int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println("executing i::"+i);
}
}
public class ThreadPool {
int nThread;
private LinkedBlockingQueue<Runnable> queue;
PoolWorker[] arr ;
public ThreadPool(int nThread) {
this.nThread = nThread;
this.queue = new LinkedBlockingQueue<>();
arr = new PoolWorker[nThread];
for(int i=0;i<nThread;i++) {
PoolWorker poolWorker = new PoolWorker();
arr[i] = poolWorker;
arr[i].start();
}
}
public void execute(Task task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
class PoolWorker extends Thread{
@Override
public void run() {
Runnable task;
while(true) {
synchronized (queue) {
while(queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
task = queue.poll();
}
task.run();
}
}
}
}
Ref: https://www.javacodegeeks.com/2016/12/implement-thread-pool-java.html
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(2);
for(int i=0;i<2;i++) {
Task task = new Task(i);
threadPool.execute(task);
}
System.out.println("done");
}
}
public class Task implements Runnable{
int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println("executing i::"+i);
}
}
public class ThreadPool {
int nThread;
private LinkedBlockingQueue<Runnable> queue;
PoolWorker[] arr ;
public ThreadPool(int nThread) {
this.nThread = nThread;
this.queue = new LinkedBlockingQueue<>();
arr = new PoolWorker[nThread];
for(int i=0;i<nThread;i++) {
PoolWorker poolWorker = new PoolWorker();
arr[i] = poolWorker;
arr[i].start();
}
}
public void execute(Task task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
class PoolWorker extends Thread{
@Override
public void run() {
Runnable task;
while(true) {
synchronized (queue) {
while(queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
task = queue.poll();
}
task.run();
}
}
}
}
Ref: https://www.javacodegeeks.com/2016/12/implement-thread-pool-java.html
No comments:
Post a Comment