Java — Thread Pools (Executor Framework) | Code Factory

Index Page : Link

Donate : Link

WordPress Blog : Link

  • Creating a new thread for every job may create performance on memory problems, to overcome this we should go for Thread Pool.
ExecutorService service = Executors.newFixedThreadPool(3);
  • We can submit a Runnable job by using a submit method service.submit(job).
package com.example.thread;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author code.factory
*
*/
public class ExecutorTest {
public static void main(String... args) {
PrintJob jobs[] = {
new PrintJob("Narendra"),
new PrintJob("Amit"),
new PrintJob("Yogi"),
new PrintJob("Rupani"),
new PrintJob("Mukesh"),
new PrintJob("Anil"),
};
ExecutorService service = Executors.newFixedThreadPool(3);
for(PrintJob job : jobs) {
service.submit(job);
}
service.shutdown();
}
}
class PrintJob implements Runnable {
String name;
public PrintJob(String name) {
this.name = name;
}

public void run() {
System.out.println(name + " job started by thread " + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}

Output :

Narendra job started by thread pool-1-thread-1
Yogi job started by thread pool-1-thread-3
Amit job started by thread pool-1-thread-2
Rupani job started by thread pool-1-thread-1
Anil job started by thread pool-1-thread-3
Mukesh job started by thread pool-1-thread-2
  • In the above exmple 3 threads are responsible to execute 6 jobs. So that a single thread can be reuse for multiple jons.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store