Chapter Sixth Task Execution
6.1 Performing tasks in threads
Serial-"Multithreading-" limited multi-threading
6.2 Executor Frame
High-load programs can be protected from excessive memory consumption through bounded queues
Java.lang.concurrent provides a thread pool as part of the implementation of the executor framework
Executor interface: Provides producer-consumer mode
Executor-based Web server:
Public class taskexecutionwebserver { private static final int nthreads = 100; private static final executor exec = Executors.newfixedthreadpool (nthreads); public static void main (String[] args) throws ioexception { serversocket socket = new serversocket (; while ) (true) { final Socket Connection = socket.accept (); runnable task = new runnable () { &nbsP;public void run () { handlerequest (Connection); } }; exec.execute (Task); } } Private static void handlerequest (socket connection) { // request-handling logic here }}
By inheriting the executor interface, different server processing methods can be implemented
Thread pool: It is closely related to task queue, where all pending tasks are saved in the work queue, the worker thread is established ahead of time, then the task execution is removed from the work queue, execution is completed again waiting for the next task, and worker threads can be reused.
Create a thread pool by calling a static method in executors: Newfixedthreadpool newcachedthreadpool newsinglethreadpool Newscheduledthreadpool
Life cycle of Executor: Lifecycle management through Executor sub-interface Executorserver
Delay tasks and cycle tasks: Timer or Replace with Scheduledthreadpoolexecutor
6.3 Finding the parallelism to use
Tasks that carry results callable and future
Callable: it thinks that the main entry point (call) will return a value or throw an exception
Future: Represents the life cycle of a task and provides a way to determine whether it has been completed or canceled
All the submit methods in Executorserver submit a runnable or callable to executor, which returns a future to get the results of the task or cancel the task. You can also explicitly instantiate a futuretask for runnable or callable
Completionserver: Executor and Blockqueue together,
Set a time limit for a task
InvokeAll
Task execution of Java Concurrent Programming practical learning Notes