Thread Java 30 days- day 9(Executor)

paul chou
1 min readAug 16, 2023

--

While using thread.start() directly to create and start threads is one appraoch, using Executor offers more advantages and control, especially when dealing with managing multiple threads. Here are some reasons why you should consider using Executor instead of just using thread.start():

Resource Management:

Using Executor allows for better management of creation and recycling. it can limit the number of threads running simultaneously, reducing excessive thread occupation of system resources.

Reusability:

Executor utilizes thread pools, enabling the reuse of existing threads, which minimizes the overhead of constantly creating and destroying threads. This is beneficial for maintaining performaince and efficiency.

  1. newFixedThreadPool(int nThreads):

Creates a fixed-size executor that can simultaneously execute a specified number of tasks.

ExecutorService executorService = Executors.newFixedThreadPool(5);
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolExample {
public static void main(String[] args) {
// Create a fixed-size thread pool with 5 worker threads
ExecutorService executorService = Executors.newFixedThreadPool(5);

// Submit tasks to the thread pool
for (int i = 0; i < 10; i++) {
Runnable task = new MyTask(i);
executorService.submit(task);
}

// Shut down the thread pool after tasks are submitted
executorService.shutdown();
}

static class MyTask implements Runnable {
private final int taskId;

MyTask(int taskId) {
this.taskId = taskId;
}

@Override
public void run() {
System.out.println("Task " + taskId + " is being executed by thread: " + Thread.currentThread().getName());
try {
Thread.sleep(1000); // Simulate task execution time
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskId + " completed.");
}
}
}

--

--