written in front of the words: I have never known the multithreaded programming related things, for threads and other related concepts are smattering. This time by preparing for the interview, plan to have some critical blind spots (in addition to multithreading, garbage collection, image caching, performance optimization, etc.) are thoroughly swept over. Next I will be organized into study notes, mainly as their study after the consolidation of the use. If can help to the same confused small white words, deeply honored, if because of lack of actual combat lead to misunderstanding or interpretation of the place, also please pass by Daniel Generous enlighten, common progress ^_^
Knowledge Point Correlation
As the starting point of this study, the thread pool is associated with a lot of concepts, such as what the thread is, often with the use of the runnable is what, why also use, and so on.
On these, I found a blog post: multithreading (thread, thread creation, threads Pool), the explanation is very comprehensive, interested in the whole read-through, it must be benefited. I am here to list only a few important and basic points, as a brief explanation of my own understanding:
- threading Thread Class : Used to create a thread (the Start method) and define the task that the thread performs (the Run method), where the Run method is equivalent to the main method in the main thread.
- Task runnable Interface : Generally there are two methods to define tasks, one is to inherit the thread class to override the Run method, and the other is to implement the Runnable interface to rewrite the Run method. The latter is used more frequently, and is commonly used to decouple the two blocks of thread creation and threading tasks .
- Task callable Interface : Similar to runnable, the call method also has the same status as the Run method, except that the callable returns the result and runnable does not return
- task result Future interface : corresponding to get the results returned by callable via the Get method of the coming interface, Note: Using the Get method will block the current thread until you get the result if you have not obtained the result.
- task Futuretask class : Can be understood as the runnable/callable and the future of the Union, through the callable (Runnable will first turn to callable) outside to add a layer, Get task results directly using the Get method
In addition to the above-mentioned classes, there are several multithreading-related concepts listed below:
- process : In short, an application corresponds to a process that consumes a certain amount of memory
- Threads : A process consists of multiple threads, which are equal to the task execution unit and do not interfere with each other
- preemptive scheduling : Allocating memory resources to threads at high and low allocations; multithreading does not increase the speed of programs, but rather improves operational efficiency and increases CPU usage
- main Thread: Running the Main method is the main threads, usually the time-consuming operations on a thread other than the main thread, to prevent blocking the main thread
Ready to finish, focus on the thread pool below ↓
Why use a thread pool
Simply put, the thread pool is like a housekeeper, dispatching and allocating work so that every servant (that is, a thread) can perform its tasks efficiently while busy, while at the same time getting full rest when idle. More specifically, there are two main points: one is to make reasonable use of existing threads, reduce the resource overhead of thread creation and destruction, speed up response, and facilitate the monitoring and management of each thread's life cycle.
Thread pool Threadpoolexecutor Class
To figure out this class, go ahead with a picture.
This is an inheritance diagram. The initial Executor interface defines the Execute method, which is relatively straightforward. Its subclass Executorservice interface, which you can understand as a generic thread pool class , adds a number of methods commonly used by the thread pool to control threads, such as Submit and shutdown, to manage the lifecycle. The inherited Abstractexecutorservice abstract class is the default implementation on the Executorservice basis. Finally,Threadpoolexecutor inherits from the abstract class and constructs a method to configure the thread pool.
Here's another way to mention the executors class, not the graph, is the thread pool factory class, which can be created through a series of static methods. Look at the source code can be found, the method is built using Threadpoolexecutor method and different configuration parameters to implement.
Here are a few of the construction methods of the Threadpoolexecutor class:
The
focuses on the third, and the other constructs are basically similar. The parameters are (in order): Number of core threads n , maximum number of threads m , timeout t , Time unit u , buffer queue b and deny processing handler . Each of these parameters represents the meaning that will be explained in the context of different buffer queue types:
- synchronousqueue Type: All tasks do not enter the buffer queue (can be understood as the buffer queue capacity is 0), directly into the available thread execution, and when there is no available thread, create a new thread to perform the task directly. When the number of threads exceeds M , call Handler to handle the new task being rejected.
- linkedblockingqueue Type: When there is a new task, a new thread is created if the current number of threads is less than n, and if it is greater than or equal to n, the buffer queue is entered, and when the buffer queue is full and the number of threads is less than M , the new thread continues to be created until M is reached and the Handler processing reject task is called. In general, the Linkedblockingqueue as an unbounded queue does not specify buffer capacity, can be infinitely extended, at this time the equivalent of M failure, but you can also specify the capacity by the constructor function.
- arrayblockingqueue Type: The rule is similar to Linkedblockingqueue, but typically specifies the queue length.
The difference between these three types of queues can be found in this article:three queues for Threadpoolexecutor
There is also a timeout of T and Time unit U, the main role is to make non-core threads idle longer than a certain length of time after automatic destruction, thereby releasing resources.
Reject Task Handler
When both the number of threads and the buffer queue are saturated, the corresponding handler is called to handle the rejected task. Here are four pre-defined processing strategies:
- In the default AbortPolicy, the exception rejectedexecutionexception is thrown directly after rejection.
- In Callerrunspolicy, the rejected task is run directly in the calling thread of the Execute method. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.
- In Discardpolicy, the task is abandoned directly after rejection.
- In Discardoldestpolicy, tasks that are at the head of the work queue (that is, the oldest) are discarded, and then retry the execution of the program (repeat this process if it fails again).
A simple example of a thread pool
Taking the Fibonacci sequence as an example, it shows the usage differences of different task types, and note that the task is submitted using submit instead of execute, and the difference is similar to callable and runnable.
1 PackageCom.effective.java.concurrent.task; 2 3 Importjava.util.concurrent.Callable; 4 Importjava.util.concurrent.ExecutionException; 5 ImportJava.util.concurrent.ExecutorService; 6 Importjava.util.concurrent.Executors; 7 Importjava.util.concurrent.Future; 8 ImportJava.util.concurrent.FutureTask; 9 Ten Public classRunnablefuturetask { One A StaticExecutorservice Mexecutor =NewThreadpoolexecutor (2, 3, 5, Timeunit.seconds,NewSynchronousqueue<runnable>()); - - the Public Static voidMain (string[] args) { - Futuredemo (); - } - + - Static voidFuturedemo () { + Try { A /** at * Submit Runnable no return value, no future data - */ -future<?> result = Mexecutor.submit (NewRunnable () { - - @Override - Public voidrun () { inFIBC (20); - } to }); + -System.out.println ("Future result from runnable:" +result.get ()); the * /** $ * Submit callable, return value, can get return value in futurePanax Notoginseng */ -future<integer> result2 = Mexecutor.submit (NewCallable<integer>() { the @Override + PublicInteger Call ()throwsException { A returnFIBC (20); the } + }); - $ System.out $. println ("Future result from callable:" +result2.get ()); - - /** the * Futuretask can be executed directly by thread wrapper or submitted to Executeservice for execution - *, and can also return the execution result through V get (), when the thread body is not completed, the main thread is blocked waiting, and the result is returned directly after execution. Wuyi */ theFuturetask<integer> Futuretask =NewFuturetask<integer>( - NewCallable<integer>() { Wu @Override - PublicInteger Call ()throwsException { About returnFIBC (20); $ } - }); - - //Submit Futuretask A Mexecutor.submit (Futuretask); +System.out.println ("Future result from Futuretask:" the+futuretask.get ()); - $}Catch(interruptedexception e) { the E.printstacktrace (); the}Catch(executionexception e) { the E.printstacktrace (); the } - } in the /** the * The Fibonacci sequence under efficiency, time-consuming Operation About * the * @paramNum the * @return the */ + Static intfibcintnum) { - if(num = = 0) { the return0; Bayi } the if(num = = 1) { the return1; - } - returnFIBC (num-1) + FIBC (num-2); the } the}
In addition to the blog post mentioned in the article, the rest of the reference blog is listed below, thank you bloggers of the selfless sharing ^_^:
Java Concurrency Programming--executor framework
Multitasking multi-threading-thread pool threadpoolexecutor-look at this, that's enough.
Multitasking with multitasking-the difference between a Java thread pool Submit and Execute
Java multithreading-thread pool Threadpoolexecutor construction methods and rules
Deep understanding of callable
The differences between runnable, callable, future, Futuretask in Java and examples