Java concurrent executor framework and thread pool

A programming method of concurrent programming is to split the task into a series of small tasks, that is, open the thread Runnable, and then submit it to an Executor (thread pool) for execution, Executor.execute(Runnalbe )  . Executor uses an internal thread pool to complete operations during execution.

1. Create a thread pool

The Executors class provides a series of factory methods for creating thread pools, and the returned thread pools all implement the ExecutorService interface.

public static ExecutorService newFixedThreadPool(int nThreads)

Create a thread pool with a fixed number of threads.

public static ExecutorService newCachedThreadPool()

Creates a cacheable thread pool, calling execute will reuse previously constructed threads (if threads are available). If no existing thread is available, a new thread is created and added to the pool. Terminates and removes threads that have not been used for 60 seconds from the cache.

public static ExecutorService newSingleThreadExecutor()

Create a single-threaded Executor.

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

Create a thread pool that supports timing and periodic task execution, which can be used to replace the Timer class in most cases.

Executor executor = Executors.newFixedThreadPool(10);
Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("task over");
    }
};
executor.execute(task);

or

1 executor = Executors.newScheduledThreadPool(10);  
2 ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;  
3 scheduler.scheduleAtFixedRate(task, 10, 10, TimeUnit.SECONDS);  

https://www.cnblogs.com/cyberniuniu/p/5021944.html

Guess you like

Origin blog.csdn.net/qq_36647209/article/details/130385343