Wednesday, 18 December 2019

How to create thread pool executor in java

package kp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyPooledThread extends Thread {

private BlockingQueue<Runnable> taskQueue = null;
private boolean isStopped = false;
CountDownLatch latch = null;

public MyPooledThread(BlockingQueue<Runnable> queue, CountDownLatch latch) {
taskQueue = queue;
this.latch = latch;
}

@Override
public void run() {
while (!isStopped()) {
try {
Runnable runnable = taskQueue.poll(5, TimeUnit.SECONDS);
if(runnable != null){
runnable.run();
doStop();
}
latch.countDown();
System.out.println("count down");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public synchronized void doStop() {
this.isStopped = true;
//this.interrupt();
}

public synchronized boolean isStopped() {
return isStopped;
}
}



-----------------------------------------------------------------------------------------------------------------


package kp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class  MyThreadPoolExecuter {

BlockingQueue<Runnable> queue = null;
List<Thread> threads = new ArrayList<Thread>();
CountDownLatch latch = null;
private boolean isStopped = false;

public MyThreadPoolExecuter(int noOfThreads, BlockingQueue<Runnable> queue, CountDownLatch latch) {
this.queue = queue;
this.latch = latch;

for (int i = 0; i < noOfThreads; i++) {
Thread t = new MyPooledThread(this.queue, latch);
threads.add(t);
t.start();
}
}

public synchronized void execute(Runnable r) {
if (this.isStopped) {
new IllegalStateException("Threadpool is stopped");
}
try {
queue.put(r);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public synchronized void stop() {
this.isStopped = true;
for (Thread thread : threads) {
((MyPooledThread)thread).doStop();
}
}
}


---------------------------------------------------------------------------------------------------------------------

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;

public class MyThreadPoolExecuterTestDrive {

public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(4);
MyThreadPoolExecuter executer = new MyThreadPoolExecuter(4,new ArrayBlockingQueue<Runnable>(4), latch);
executer.execute(()->{
System.out.println("I am thread 1");
});
executer.execute(()->{
System.out.println("I am thread 2");
});
executer.execute(()->{
System.out.println("I am thread 3");
});
executer.execute(()->{
System.out.println("I am thread 4");
});
executer.execute(()->{
System.out.println("I am thread 5");
});
try {
latch.await();
//executer.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

No comments:

Post a Comment