Basic concepts
Threads do not have the same concept as tasks.
Tasks: Often abstract and discrete units of work, such as in Web requests, where a request for a user needs to return the corresponding page is a task, and the Java class that implements Runnable the interface in is also a task.
Threads: An entity that performs a task that can perform tasks serially in a single thread, such as a single-threaded serial execution of a Web request, or a thread execution for each request.
A task is a set of logical units of work, while a thread is the mechanism by which the task executes asynchronously.
A simple example: when we define an Runnable object, that is, the task is executed using the new Thread(Runnable).start() impending task into the actual thread.
Executor thread pool
There are two strategies for performing tasks in Web apps:
-
Put all tasks in a single thread for serial execution: poor responsiveness and throughput.
-
Create a thread-parallel execution for each task: the complexity of resource management, which reflects the high overhead and instability of the threads.
So, in the introduction of the Java Executor (thread pool) framework to simplify the management of threads, Executor using runnable as its basic task representation, in the Java class library, the main abstraction of task execution is not Thread , but Executor .
ExecutorBased on the producer-consumer model, the actions that are submitted for the task are equivalent to the producer (generating the unit of work to be completed), and the thread that performs the task is the consumer (after executing these units of work), which decouples the submission of the request processing task from the actual execution of the task. In the example below, a fixed-length thread pool can be set up to accommodate 100 threads.
class TaskExecutionWebServer { private static final int NTHREADS = 100; // 调用Executors中的静态工厂方法可以来创建一个线程池 private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); public static void main(String[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handleRequest(connection); } }; // 通过execute将任务提交到工作队列中,工作线程反复获取执行 exec.execute(task); } }}
Execution policy
A thread pool is a resource pool that manages a set of homogeneous worker threads. By reusing an existing thread instead of creating a new thread, you can distribute the huge overhead incurred during thread creation and destruction while processing multiple requests. Another additional benefit is that when the request arrives, the worker thread already exists because of the increased responsiveness.
- Work queue: The thread pool is closely related to the work queue, where all the tasks awaiting execution are saved in the work queue.
- Worker thread: Gets a task from the work queue, executes the task, and then returns to the thread pool and waits for the next task.
In the execution strategy, the "What, Where, when, how" of task execution is defined, including:
- The thread in which the task executes
- The order in which tasks can be executed (such as priority, FIFO, LIFO)
- How many tasks can be executed concurrently
- ......
Life cycle
Thread pool life cycle (Executorservice)
We already know how to create a executor, but don't discuss how to close it. To address the life cycle of service execution, executor extends the Executorservice interface and adds some methods for life cycle management.
public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownNow(); boolean isShutdown(); //...}
The Executorservice life cycle has 3 states: Run, off, and terminated. The shutdown () method performs a gentle shutdown process: No longer accepts new tasks while waiting for committed tasks to complete (including tasks that do not start). Shutdownnow () will attempt to cancel all running tasks. is closed and then committed, handled by the "refuse to execute processor", or throws a Rejectedexecutionexception exception.
Task life cycle (future)
Because runnable cannot return a value or throw a checked exception, there are significant limitations. So the callable is introduced, and it is assumed that the main entry point (that is, call) will return a value and possibly throw an exception.
Runnable and callable descriptions are abstract computational tasks, typically created, submitted, started, and completed in four stages, such as Executorservice for Executor to solve the life cycle problem, the future also for a task to solve the life cycle of the problem, It also provides a way to determine whether it has been completed or canceled, and to obtain the results of the task and cancel the task.
public interface Callable<V> { V call() throws Exception;}public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); // 取消任务 boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionExeception, CancellationExeception; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionExeception CancellationExeception, TimeoutException;
By calling Executorservice The Submit method returns a future representing the life cycle of the task, which can be used to obtain the result of the task or cancel the task. It is also possible to instantiate a futuretask for a specified runnable or callable.
In the process of committing runnable or callable to executor, a secure release process is included, and the runnable or callable is posted from the submission thread to the thread that ultimately performs the task. Similarly, a security release is included in the process of acquiring future results, which is to publish the result from the thread that computes it to any thread that obtains it through get.
Reference: Books Java Concurrency in practice
Java Multithreading Basic Concepts