Wednesday, June 5, 2019

Thread Pool - ThreadPoolExecutor Example

  Java Thread Pool - ThreadPoolExecutor Example  

 WorkerThread.java

package com.shubh.threadpool;

public class WorkerThread implements Runnable {

 private String command;

 public WorkerThread(String s) {
  this.command = s;
 }

 @Override
 public void run() {
  System.out.println(Thread.currentThread().getName() + " Start. Command = " + command);
  processCommand();
  System.out.println(Thread.currentThread().getName() + " End.");
 }

 private void processCommand() {
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 @Override
 public String toString() {
  return this.command;
 }
}

TestThreadPool.java

package com.shubh.threadpool;

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

public class TestThreadPool {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

  Output:  

pool-1-thread-4 Start. Command = 3
pool-1-thread-2 Start. Command = 1
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-2 Start. Command = 5
pool-1-thread-1 Start. Command = 6
pool-1-thread-3 Start. Command = 7
pool-1-thread-5 End.
pool-1-thread-4 End.
pool-1-thread-5 Start. Command = 8
pool-1-thread-4 Start. Command = 9
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-4 End.
pool-1-thread-5 End.
Finished all threads

Q- How To Create custom thread Pool in java?
http://www.javaiq.in/2019/06/how-to-create-custom-thread-pool.html

No comments:

Post a Comment