Saturday, 11 January 2014

Advanced Java_ Multi-threading Part 5 -- Thread Pools


==
package Demo7;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Title -- Advanced Java_ Multi-threading Part 5 -- Thread Pools Note:--
 * 
 * @author Dharmaraj.Net
 */
public class App {
 public static void main(String[] args) {
  ExecutorService executor = Executors.newFixedThreadPool(2); // Two
                 // factor
                 // workers
                 // two
                 // threads
  for (int i = 0; i < 5; i++) {
   executor.submit(new processor(i));
  }
  executor.shutdown();
  System.out.println("All task submited");
  try {
   executor.awaitTermination(1, TimeUnit.DAYS);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  
  System.out.println("All task completed");
 }
}

class processor implements Runnable {

 private int id;

 public processor(int id) {
  this.id = id;
 }

 public void run() {
  System.out.println("Starting :" + id);
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("Complet :" + id);
 }

}

No comments:

Post a Comment