티스토리 뷰

Java

[Java] Executor

snail voyager 2023. 11. 20. 20:07
728x90
반응형

Executor

In Java, the Executor framework provides a simple and flexible interface for asynchronous task execution. It is part of the java.util.concurrent package and is commonly used to manage and control the execution of tasks concurrently. The primary interface in the Executor framework is the Executor interface, and there are several implementations available.

 

Basic Usage of Executor

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ExecutorExample {

    public static void main(String[] args) {
        // Creating an Executor (using a fixed-size thread pool with 5 threads)
        Executor executor = Executors.newFixedThreadPool(5);

        // Submitting a task to the Executor
        executor.execute(() -> {
            // Task logic goes here
            System.out.println("Task executed by thread: " + Thread.currentThread().getName());
        });
    }
}

Common Implementations of Executor

Executors.newFixedThreadPool(int nThreads):

Creates a fixed-size thread pool where the number of threads remains constant.

Executor executor = Executors.newFixedThreadPool(5);

Executors.newCachedThreadPool():
Creates a thread pool that creates new threads as needed but reuses existing threads when they are available.

Executor executor = Executors.newCachedThreadPool();

Executors.newSingleThreadExecutor():
Creates a single-threaded executor that uses a single worker thread to execute tasks sequentially.

Executor executor = Executors.newSingleThreadExecutor();

Executors.newScheduledThreadPool(int corePoolSize):
Creates a thread pool that can schedule commands to run after a given delay or to execute periodically.

Executor executor = Executors.newScheduledThreadPool(3);

ExecutorService

ExecutorService is a subinterface of Executor that provides additional features such as task submission with a Future object, task cancellation, and more.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {

    public static void main(String[] args) {
        // Creating an ExecutorService (using a fixed-size thread pool with 3 threads)
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // Submitting a task to the ExecutorService and obtaining a Future object
        executorService.submit(() -> {
            // Task logic goes here
            System.out.println("Task executed by thread: " + Thread.currentThread().getName());
        });

        // Shutdown the ExecutorService when no more tasks need to be submitted
        executorService.shutdown();
    }
}

ScheduledExecutorService

ScheduledExecutorService extends ExecutorService and provides scheduling capabilities for delayed and periodic task execution.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceExample {

    public static void main(String[] args) {
        // Creating a ScheduledExecutorService with a single thread
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        // Scheduling a task to run after an initial delay of 1 second, and then every 3 seconds
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            // Task logic goes here
            System.out.println("Task executed by thread: " + Thread.currentThread().getName());
        }, 1, 3, TimeUnit.SECONDS);

        // Shutdown the ScheduledExecutorService when no more tasks need to be scheduled
        scheduledExecutorService.shutdown();
    }
}

 

728x90
반응형

'Java' 카테고리의 다른 글

[Java] DateTimeFormatter uuuu vs yyyy  (1) 2023.11.23
[Java] Java 동시성  (0) 2023.11.20
[Java] EnumSet, EnumMap  (0) 2023.10.29
[Java] 날짜, 시간 API  (0) 2023.10.18
[Java] Lambda 표현식으로 리펙토링  (1) 2023.10.12
반응형
300x250