Wednesday, 6 January 2016

Create Threads Using java.util.concurrent.ThreadFactory


By implementing java.util.concurrent.ThreadFactory interface, we can create threads on demand. By implementing ThreadFactory interface, we are following Factory design pattern, which is used to encapsulate the processes involved in the creation of objects.

public class Producer implements Runnable {

 @Override
 public void run() {
  System.out.println(Thread.currentThread().getName()
    + " running the task");
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(Thread.currentThread().getName()
    + " produced the data");
 }

}

public class Consumer implements Runnable {

 @Override
 public void run() {
  System.out.println(Thread.currentThread().getName()
    + " running the task");
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(Thread.currentThread().getName()
    + " consumed the data");
 }

}

public class WorkerThreadFactory implements java.util.concurrent.ThreadFactory {

 private static int id = 0;
 private String prefix = "";

 public WorkerThreadFactory(String prefix) {
  this.prefix = prefix;
 }

 @Override
 public Thread newThread(Runnable r) {
  id++;
  return new Thread(r, prefix + " " + id);
 }

}

public class ThreadFactoryDemo {
 public static void main(String args[]) {
  WorkerThreadFactory producerFactory = new WorkerThreadFactory(
    "producer");
  WorkerThreadFactory consumerFactory = new WorkerThreadFactory(
    "consumer");

  producerFactory.newThread(new Producer()).start();
  producerFactory.newThread(new Producer()).start();
  producerFactory.newThread(new Producer()).start();

  consumerFactory.newThread(new Consumer()).start();
  consumerFactory.newThread(new Consumer()).start();
  consumerFactory.newThread(new Consumer()).start();
 }
}


Sample Output
producer 3 running the task
producer 1 running the task
producer 2 running the task
consumer 4 running the task
consumer 5 running the task
consumer 6 running the task
consumer 6 consumed the data
consumer 4 consumed the data
consumer 5 consumed the data
producer 3 produced the data
producer 1 produced the data
producer 2 produced the data



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment