Terminating threads
Hi,
I have developed a simple program to test executor service and executors for thread pool creation and management. The program executes fine until I call the shudown() method. The Executor is shutdown but the threads still remain alive (verified by calling Shutdown() -> isShutdown() -> isTerminated())
I have supplied the code along with this message:
import java.util.concurrent.*;
publicclass PerfTrack{
publicstaticvoid main(String args[]){
finalint CAPACITY = 5;
final ExecutorService threadPool;
Tasks hasTasks =new Tasks();
ArrayBlockingQueue taskQueue =new ArrayBlockingQueue(CAPACITY,true);
threadPool = Executors.newFixedThreadPool(10);
threadPool.execute(new Scheduler(taskQueue));
while(hasTasks.getTasks())
threadPool.execute(new Handler(taskQueue, hasTasks));
threadPool.shutdown();
System.out.println("hello");
System.out.println(threadPool.isShutdown());
System.out.println(threadPool.isTerminated());
}
}
class Tasks{
privateboolean hasTasks;
public Tasks(){
hasTasks =true;
}
publicsynchronizedboolean getTasks(){
return hasTasks;
}
publicsynchronizedvoid setTasks(){
hasTasks =false;
}
}
class Schedulerimplements Runnable{
private ArrayBlockingQueue taskQueue;
public Scheduler(ArrayBlockingQueue taskQueue){
this.taskQueue = taskQueue;
}
privatevoid createTasks(){
for(int i = 1; i <= 20; i++){
try{
taskQueue.put(new Integer(i));
if(i == 20){
taskQueue.put(new Integer(0));
}
}
catch(InterruptedException intEx){
// Do nothing
}
}
}
publicvoid run(){
createTasks();
}
}
class Handlerimplements Runnable{
private ArrayBlockingQueue taskQueue;
private Integer queueItem;
volatile Tasks hasTasks;
public Handler(ArrayBlockingQueue taskQueue, Tasks hasTasks){
this.taskQueue = taskQueue;
this.hasTasks = hasTasks;
}
privatesynchronizedvoid getItems(){
try{
queueItem = (Integer)taskQueue.take();
if(queueItem.intValue() == 0){
hasTasks.setTasks();
}
else
System.out.println("The number is:\t" + queueItem.intValue());
}
catch(InterruptedException intEx){
//
}
}
publicvoid run(){
getItems();
}
}
Your help is greatily appreciated,
Thanks

