Monday, June 20, 2011

SingleThreadPool Example

This article will discuss about Thread pool that uses single thread to execute tasks. From Java 5.0+ one can get such pool from Executors using following method –
public static ExecutorService newSingleThreadExecutor()

It creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Example
Here is our worker thread:
public class WorkerThread implements Runnable {
    private int workerNumber;

    WorkerThread(int number) {
        workerNumber = number;
    }

    public void run() {
        for (int i=0;i<=100;i+=20) {
        // Perform some work ...
            System.out.println("Worker number: " + workerNumber
                + ", percent complete: " + i );
            try {
                Thread.sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {
            }
        }
    }
}

This is our SingleThreadPoolDemo
public class SingleThreadPoolCemo {
   public static void main(String[] args) {
      ExecutorService svc = Executors.newSingleThreadExecutor();

      for(int i=0;i<4;i++){
         svc.submit(new Boogie(i));
      }
      svc.shutdown();

      System.out.println("Done work by workers");
   }

}

No comments:

Post a Comment

Chitika