Course Content
Advanced Java 2077
Advanced Java 2077
Thread Pools and Executors
Thread pools and executors provide a way to manage and reuse threads in concurrent programming in Java. In this chapter, we will discuss the use cases of thread pools and executors and how to use them in Java, including complete code examples.
Use Cases of Thread Pools and Executors
Thread pools and executors are used in scenarios where creating and destroying threads frequently can be expensive. By reusing threads, we can improve performance and reduce resource usage. Some common use cases for thread pools and executors include:
- Handling multiple client connections in a server
- Performing batch processing of large amounts of data
- Implementing parallel algorithms
Executor Interface
The Executor
interface defines a simple API for executing tasks asynchronously in a separate thread.
Here's an example of using the Executor
interface to execute a simple task.
Main
import java.util.concurrent.Executor; import java.util.concurrent.Executors; class MyTask implements Runnable { public void run() { System.out.println("Hello, world!"); } } public class ExecutorExample { public static void main(String[] args) { Executor executor = Executors.newSingleThreadExecutor(); executor.execute(new MyTask()); } }
In this example, we create a MyTask
class that implements the Runnable
interface and prints "Hello, world!"
when executed. We then create an executor using the Executors
class and execute the MyTask
instance using the execute method.
Thread Pools
Thread pools are a type of executor that manages a pool of threads, which can be reused to execute tasks. Here's an example of using a thread pool to execute multiple tasks.
Main
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MyTask implements Runnable { private int taskId; public MyTask(int taskId) { this.taskId = taskId; } public void run() { System.out.println("Task " + taskId + " started."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task " + taskId + " finished."); } } public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); for (int i = 0; i < 4; i++) { executor.execute(new MyTask(i)); } executor.shutdown(); } }
In this example, we create a MyTask
class that takes an ID
as a constructor parameter and sleeps for one second before printing a message indicating that the task is finished. We then create a thread pool with a fixed size of 2 using the Executors
class and execute 4 instances of MyTask
using the execute method. Finally, we shut down the thread pool using the shutdown method.
Thanks for your feedback!