Java concurrent programming combat notes: task execution

executor framework

The executor framework separates the submission and execution of tasks, and the submission of tasks will be spread all over the program, but the execution strategy can be set in one place, such as using thread pool execution or serial execution, thread pool fixed length or variable length, all The excutor framework should be considered where new Thread(task) is used explicitly

Task callables and futures that carry results

There are three methods for the construction of thread execution tasks: 1. Inherit thread. 2. Implement the runnable interface. 3. Implement the callable interface. The abstraction of callable can have a return value to represent the result of the task. Submit the callable task in the excutor and return the Future object. The Future object wraps the life cycle of the entire task and can obtain the return value.

Task execution exception

The get of Future obtains the execution result of the callable and will throw In'te'rru'p'tedException, ExecutionException, Can'ce'lationException, TimeoutException

When an exception is thrown in the task, when calling the get of Future to get the result, an ExecuteException will be thrown, and you can call e.getCause to get the real exception.

CompletionService

If there are multiple parallel tasks, call the get of the corresponding Future one by one when obtaining the result. If it needs to be completed first, this method cannot be done. CompletionService can be used, an excutor is associated internally to submit tasks, and the take method of CompletionService is called to return the Future structure of the completed task

Set time limits for tasks

The get method of Future can set the timeout, and can also call the cancel method (usually the cancel method will be called after the timeout)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325881365&siteId=291194637