Thread Pools
Thread pools are used to manage a pool of worker threads. This tutorial will teach you how to use thread pools in Java.
Using ExecutorService
The ExecutorService
interface provides methods for managing termination and methods that can produce a Future
for tracking progress of one or more asynchronous tasks:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
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");
}
}
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String message) {
this.message = message;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + message);
processMessage();
System.out.println(Thread.currentThread().getName() + " (End)");
}
private void processMessage() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In this example, the ExecutorService
manages a pool of threads that execute the WorkerThread
instances.
Scheduled Thread Pool
The ScheduledExecutorService
interface is a subinterface of ExecutorService
, which supports future and periodic task execution:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
public void run() {
System.out.println("Executing task at " + System.nanoTime());
}
};
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
}
}
In this example, a task is scheduled to run at a fixed rate of one second using a scheduled thread pool.
Continue exploring our intermediate tutorials to learn more about Java programming.