Java Multithreading and thread pool

Source: Internet
Author: User
Tags terminates


The concept of multithreading is very good understanding is that multiple threads exist at the same time, but to use good multithreading is not easy, involving multi-threaded communication, multi-thread sharing a resource and many other problems.

Advantages and disadvantages of using multithreading:
1) Improve the execution efficiency of the program (simultaneous execution of multiple threads).
2) Appropriate increase in resource utilization (CPU, memory, etc.).
1) occupy a certain amount of memory space.
2) The more threads the CPU is, the greater the scheduling overhead.
3) The complexity of the program will increase.

For multi-threaded sample code interested can write their own demo, to run the experience, below I mainly list some of the technical points of multithreading.


Synchronization block Everyone is more familiar with the Synchronized keyword to achieve, all add synchronized method and block statement, when the multi-threaded access, at the same time only one thread can access.

Wait (), notify (), Notifyall ()

These three methods are the final native method of Java.lang.Object, and any class that inherits Java.lang.Object has these three methods. They are the underlying mechanism provided by the Java language to implement inter-threading blocking and control in-process scheduling, which we rarely use at times.

Wait ():
Causes the thread to enter a wait state until it is awakened by another thread through notify () or Notifyall, which can only be called in a synchronous method.

Notify ():
Randomly selects a thread that calls the wait method on the object, unblocking its blocking state, which can only be called inside a synchronous method or synchronous block.

Notifyall ():
All those threads that call the wait method on the object are unblocked, and the method can be called only within the synchronization method or synchronization block.

Call any of these three methods, the current thread must be the holder of the lock, and if it does not throw a illegalmonitorstateexception exception.

The difference between wait () and thread.sleep (long time)

Sleep (): Allows the currently executing thread to hibernate (suspend execution) for a specified number of milliseconds without losing ownership of any monitor, and sleep () is a static method dedicated to the thread class for a particular thread.
The wait () method suspends the execution of the thread in the entity, causing the object to enter a wait state until the wait time of the Notify () method notification or wait () is reached. The sleep () method suspends the thread that is held to run, causing the thread to hibernate until the time of hibernation or sleep is interrupted by the interrupt method.
The wait () method releases the synchronization lock when it enters the waiting state, and the sleep () method does not release the synchronization lock. So, when there is no one to interrupt it when a thread has infinite sleep, the program is in great Trouble, notify () is used to inform the thread, but the thread needs to get lock before notify (). Another meaning must be written in synchronized (Lockobj) {...}. Wait () is also the case where a thread needs to release a lock, and it can be freed only if it obtains lock, so wait () also needs to be placed in synchronized (Lockobj) {...}.

volatile keyword

Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs. The volatile variable guarantees that the next read operation will occur after the previous write operation. The thread will read the variable directly from memory and does not cache it. This ensures that the variables read by the thread are consistent with the memory.

ThreadLocal variable

ThreadLocal is a special variable in Java. Each thread has a ThreadLocal that each thread has its own independent variable, and the race condition is completely eliminated. If you provide a copy of your own unique variables for each thread, you will be much more efficient. First, it reduces the number of expensive objects created by multiplexing. Second, you get thread safety without using high-cost synchronization or immutability.

Join () method

The join () method is defined in the thread class, so the caller must be a thread, and the join () method is basically to get the thread that invokes the method to complete the contents of the run () method, then execute the code after the join () method, and look at the following "meaning" code:

new Thread(计数线程一);  new Thread(计数线程二);  t1.start();  t1.join// 等待计数线程一执行完成,再执行计数线程二t2.start();

After starting T1, the Join () method is called until the count task of T1 ends, the T2 starts, and then T2 starts counting tasks, and two threads are executed in strict order. If the execution of T2 depends on the complete data in T1, this method can ensure the synchronization of the two threads well.

Thread.yield () method

Thread.Sleep (long): Thread temporarily terminates execution (sleep) for a certain amount of time.
Thread.yield (): The thread discards the run and yields the control of the CPU.

Both of these methods will give the CPU control of the current running thread, but the sleep () method will not be able to get a running chance in the specified sleep time until its sleep time is complete, and the yield () method gives out control, it is possible to be immediately selected to run by the system scheduling mechanism, for example, The thread that executes the yield () method takes precedence over other threads, and the thread may not have the effect of giving up control of the CPU even if the yield () method is executed, since it gives control and enters the queued queue, The scheduling mechanism will select one of the highest-ranked threads from the queue waiting to run, and it is (probably) selected to run.


Thread Scheduling Policy

(1) Preemptive scheduling strategy

The thread scheduling algorithm for the Java Runtime system is preemptive. The Java runtime system supports a simple fixed-priority scheduling algorithm. If a thread that has a higher priority than any other thread that is in a running state is in a ready state, the runtime chooses that thread to run. The new higher-priority thread preempted the other threads. However, the Java runtime system does not preempt the same priority thread. In other words, the Java Runtime system is not time-sharing. However, the implementation system based on the Java thread class may support ticks, so do not rely on ticks when writing code. The thread scheduler takes a simple, non-preemptive, round-robin scheduling sequence when the ready-to-use threads in the system have the same priority.

(2) Time-slice rotation scheduling strategy

The thread scheduling of some systems adopts time slice rotation scheduling strategy. This scheduling strategy is to select the highest-priority thread from all the threads in the ready state to allocate a certain amount of CPU time to run. Select another thread to run after that time. A low-priority thread will only be able to execute if the thread is running to end, give up (yield), or get into a blocking state for some reason. If two threads with the same priority are waiting for the CPU, the scheduler selects the running thread in a round-robin fashion.

Benefits of thread pool thread pool

1) Avoid the performance overhead associated with creating and destroying threads.
2) Avoid blocking phenomena caused by a large number of threads that preempt system resources.
3} Enables simple management of threads and provides functions such as timed execution, interval execution, and so on.

One more concept

Java inside the thread pool of the top interface is Executor, but the real thread pool interface is Executorservice, executorservice default implementation is threadpoolexecutor; Normal class executors is called Threadpoolexecutor.

As a usual look at the source code of each interface:

 Public  interface Executor { void execute(Runnable command) ;} Public  interface executorservice extends Executor { void shutdown() ;list<runnable> shutdownnow() ; boolean isshutdown() ; boolean isterminated() ; <T>future<t> Submit(callable<t> Task) ; <T>future<t> Submit(Runnable task, T result) ;    Future<?> Submit (Runnable Task); ...} Public  class executors {Public   static executorservice newcachedthreadpool() {return NewThreadpoolexecutor (0, Integer.max_value,60L, Timeunit.seconds,NewSynchronousqueue<runnable> ()); }    ...}

Here's a thread pool I created:

ExecutorService pool = Executors.newCachedThreadPool();

Executors provides four thread pools:

    • 1) Newcachedthreadpool is a thread pool that can create new threads as needed, but is reused when previously constructed threads are available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance. Calling execute () reuses the previously constructed thread (if the thread is available). If an existing thread is not available, a new thread is created and added to the pool. Terminates and removes from the cache those threads that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note that you can use the Threadpoolexecutor construction method to create a thread pool with similar attributes but with different details, such as time-out parameters.

    • 2) Newsinglethreadexecutor Create is a single-thread pool, that is, the pool is only one of the threads at work, all the tasks are executed serially, and if this unique thread ends up as an exception, then there will be a new thread to replace it, This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.

    • 3) Newfixedthreadpool Create a fixed-size thread pool, create a thread each time a task is committed, and until the thread reaches the maximum size of the threads pool, the size of the thread pool remains the same once the maximum is reached, and if a thread ends up performing an exception, The thread pool will then replenish a new thread.

    • 4) Newscheduledthreadpool creates a thread pool of unlimited size, which supports timing and the need to perform tasks periodically.

Using the Threadpoolexecutor constructor, the concept of thread pool related parameters is:

public ThreadPoolExecutor(int corePoolSize,                          int maximumPoolSize,                          long keepAliveTime,                          TimeUnit unit,                          BlockingQueue<Runnable> workQueue,                          ThreadFactory threadFactory) {    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,         threadFactory, defaultHandler);}
    • 1) Corepoolsize: The thread pool core number of threads, in general, regardless of whether or not the task will always be alive in the thread pools, only in the Threadpoolexecutor method Allowcorethreadtimeout (Boolean Value) is set to true, the idle core thread will have a timeout mechanism, and the core thread will be terminated if no new task is present at the specified time, and this interval is specified by the 3rd attribute KeepAliveTime.

    • 2) Maximumpoolsize: The maximum number of threads that the thread pool can hold, and when the number of active threads reaches this value, subsequent new tasks will be blocked.

    • 3) KeepAliveTime: Controls the timeout length when the thread is idle, and terminates the thread. Typically used for non-core threads, the core thread is also used when the method Allowcorethreadtimeout (boolean value) in Threadpoolexecutor is set to true.

    • 4) Unit: Used to specify the time unit of the KeepAliveTime parameter, Timeunit is an enum enumeration type, commonly used are: timeunit.hours (Hours), timeunit.minutes (minutes), Timeunit.seconds (seconds) and timeunit.milliseconds (milliseconds).

    • 5) WorkQueue: The thread pool's task queue, which is stored in the queue by the Execute (Runnable command) method of the thread pool, Runnable the task.

    • 6) Threadfactory: Thread Factory, which is an interface that is used to create new threads for the thread pool.

Shutdown of the thread pool

Threadpoolexecutor provides two methods for closing the thread pool, respectively, shutdown () and Shutdownnow ().

Shutdown (): Does not terminate the thread pool immediately, but waits until all tasks in the task cache queue have been executed before terminating, but will no longer accept new tasks.
Shutdownnow (): Terminates the thread pool immediately, attempts to break the task that is being performed, and empties the task cache queue, returning tasks that have not yet been performed.

Interview questions

1) What is the Executor framework?

The Executor framework is introduced in Java 5 and the Executor Framework is a framework for executing asynchronous tasks called, dispatched, executed, and controlled by a set of policies.

Unlimited creation of threads can cause application memory overflow, so creating a thread pool is a better solution because you can limit the number of threads and recycle those threads. The Executor framework makes it very easy to create a thread pool.

2) What is the executors class?

Executors provides tools for the executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes. Executors can be used to create a thread pool conveniently.

Wen/Sun Fusheng Weibo (author of Jane's book)
Original link:
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Java Multithreading and thread pool

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.