Java — Thread Pools (Executor Framework) | Code Factory

ExecutorService service = Executors.newFixedThreadPool(3);
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();
}
}
}
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

--

--

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