Multithreaded programming learning ten (thread pool principle)

1、 Thread pool workflow

Tips: This design scheme can avoid frequent thread creation, and most work tasks will stay in the second step.

2、 Executor framework

In Java, the knowledge of thread pool is to be expanded from the executor framework. The executor framework is mainly composed of three parts:

1. Tasks

Including runnable interface or callable interface. The runnable interface has no return value, and the callable interface has a return value.

// Runnable 和 Callable 都可以直接被 ThreadPoolExecutor 和 ScheduledThreadPoolExecutor 执行
Runnable runnable = () -> System.out.println(123);
// Executors 可以将 Runnable 转化成 Callable
Callable<Object> callable = Executors.callable(runnable);
Callable<String> success = Executors.callable(runnable,"success");

2. Implementation of the mandate

It includes the core interface executor of task execution mechanism, executorservice interface inherited from executor, ThreadPoolExecutor and scheduledthreadpoolexecutor that implement executorservice.

ThreadPoolExecutor is the core implementation class of thread pool, which is used to execute the submitted task. The principle of ThreadPoolExecutor is the thread pool workflow described above.

Scheduledthreadpoolexecutor inherits from ThreadPoolExecutor and can execute tasks after a given delay or periodically.

Executors are factory classes that create ThreadPoolExecutor and scheduledthreadpoolexecutor.

static ExecutorService executorService = Executors.newFixedThreadPool(5);

3. Results of asynchronous calculation

It includes the future interface and the futuretask class that implements future.

// 执行 Runnable
executorService.execute(runnable);
// 执行 Callable
Future<Object> submit = executorService.submit(callable);
// Future 的 get 方法会阻塞线程直到完成
System.out.println(submit.get());
Future<String> future = executorService.submit(success);
System.out.println(future.get());

When futuretask is not started, execute futuretask The cancel () method will cause this task to never be executed; When futuretask is started, execute futuretask The cancel (true) method will attempt to stop the task by interrupting the thread executing the task; when futuretask is in the started state, the execution of futuretask.cancel (false) method will not affect the thread executing the task (let the running task complete); when futuretask is in the completed state, execute futuretask.cancel The () method will return false.

The usage diagram of the executor framework is as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>