ThreadPool – Example

package org.nikias.concurrent.util.test;

import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorSample {

 private Executor executorEngine;

 public ExecutorSample() {
  executorEngine = new ThreadPoolExecutor(5, 10, 100,
    TimeUnit.MICROSECONDS, new SynchronousQueue<Runnable>());
 }

 public void add(Runnable task) {
  executorEngine.execute(task);
 }

 public static void main(String args[]) {
  ExecutorSample executor = new ExecutorSample();
  for (int i = 0; i < 10; i++) {
   Runnable task = getRunnableTask();
   executor.add(task);
  }
 }

 private static Runnable getRunnableTask() {
  Runnable task = new Runnable() {
   public void run() {
    long d = (long) (Math.random() * 10000);
    System.out.println(“Thread (”
      + Thread.currentThread().getName() + “) Id is : ”
      + +Thread.currentThread().getId()
      + ”  :: Generated a random : ” + d);
    try {
     Thread.sleep(d);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    System.out.println(“Thread (”
      + Thread.currentThread().getName() + “) Id is : ”
      + +Thread.currentThread().getId()
      + ” :: Completes the task”);
   }
  };
  return task;
 }
}

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: