Multithreaded programming learning three (communication between threads)

1、 Summary

2、 Waiting / notification mechanism

1. "Wait / notify" mechanism: wait / notify mechanism. Wait causes the thread to suspend running, while notify causes the suspended thread to continue running. Use the interaction between a cook and a waiter to illustrate:

(1) The time the waiter takes the dishes depends on the cook, so the waiter has a "wait" state.

(2) The chef puts the dishes on the "dish delivery desk", which is actually equivalent to a notice. At this time, the waiter can get the dishes and give them to the diner.

2、wait()

(1) Causes the thread currently executing code to wait. The wait () method is a method of the object class. It is used to put the current thread into the "pre execution queue" and stop execution at the code line where the wait () is located until it receives a notification or is interrupted.

(2) before calling the wait () method, the thread must get the object level lock of the object, that is, the wait () method can only be invoked in the synchronization method or synchronous block, otherwise the IllegalMonitorStateException exception will be thrown. (it belongs to a subclass of runtime and does not require a try catch statement to catch exceptions)

Tips: why do you have to lock when calling the wait () method? First of all, wait () and notify () belong to object methods, not thread methods. They only recognize the object class, not the thread class. Second: the wait () method must match the noyify () method to realize inter thread communication. So! How can the notify () method belonging to the same object class know which wait () to wake up? It is judged by the locking mechanism! Otherwise, wouldn't a notifyAll () wake up all the waiting wait () threads, even for different locks?

(3) After calling the wait () method, the current thread releases the lock, and this object will enter the thread waiting pool and wait to be awakened. Before returning from wait (), the thread competes with other waiting threads to regain the lock.

(4) The wait () method can be interrupted by interrupt and throw an interruptedexception.

(5) Wait (long): the function of the wait (long) method with one parameter is to wait for whether a thread wakes up the lock within a certain time. If it exceeds this time, it will wake up automatically.

3、notify()

(1) Used to notify other threads that may be waiting for object locks on the object. If there are multiple threads waiting, the thread planner randomly selects one of the threads in the wait state, notifies it, and makes it wait to obtain the object lock of the object. (note! What we are talking about here is waiting, that is, after the notify () method is executed, the current thread will not immediately release the object lock, that is, the thread in wait () status will not immediately obtain the object lock, and the lock needs to be released after the code in the synchronized code block is executed!)

(2) it must also be invoked in synchronous or synchronous blocks, that is, before the call, the thread must also get the object level lock of the object, otherwise it will also throw IllegalMonitorStateException..

(3) When notify () issues a notification, but no wait () thread is waiting, it has no effect.

4、notifyAll()

5、

6. False death: the phenomenon of "false death" is actually that the thread enters the waiting state. If all threads enter the waiting state, the program will no longer perform any functions, and the whole project is stopped. The reason for this is: for example, the problem of multiple producers and consumers, the "producer" may wake up the "producer", and the "consumer" may wake up the "consumer", which wakes up the same kind, resulting in the thread constantly waiting. How to solve this problem? Just change notify () to notifyAll (), that is, wake up different classes together.

7. Pipestream in Jave is a special stream that can be used to transfer data directly in different threads. One thread sends data to the output pipeline, and another thread reads data from the input pipeline. By using pipes, communication between different threads can be realized without the help of things like temporary files. JDK provides four classes to enable communication between threads, including byte stream (pipedoutputstream, pipedinputstream) and character stream (pipedwriter, pipedereader).

3、 Use of method join

1. In many cases, the main thread creates and starts a child thread. If a large number of time-consuming calculations are to be performed in the child thread, the main thread will often end before the end of the child thread. At this time, if the main thread wants to wait for the execution of the child thread to finish, for example, the child thread processes a data, and the main thread needs to use the join () method to obtain the value in the data.

2. The function of join () is to wait for the thread to be destroyed and block the current thread indefinitely. Wait for the thread of join () to be destroyed before continuing to execute the code of the current thread.

3. Similarly, the join () method can be interrupted by the interrupt () method and throw an interruptedexception exception.

4. The join () method is a concise application of the wait / notify paradigm. When the child thread calls join (), the main thread executes the wait () method to enter the wait and release the lock. Zi Xiancheng gets the lock. After execution, he calls the notifyAll () method to release the lock. The main thread then executes.

5. What is the difference between join and synchronized?

(1) Join () internally uses the wait () method to wait.

(2) The synchronized keyword uses the object monitor principle as synchronization.

6. What is the difference between join (long) and sleep (long)?

(1) Join (long) is internally implemented by the wait (long) method. When the wait (long) method is executed, the lock of the current thread is released, and other threads can also call the synchronization method in this thread. That is, after joining (long), the thread releases the lock and needs to compete with other threads for lock resources.

(2) Thread. The sleep (long) method does not release the lock.

4、 Use of ThreadLocal class

1. Variable values can be shared in the form of public static variables. All threads use the same public static variable. If you want to realize that each thread has its own shared variables, how to solve it? The ThreadLocal class solves the problem that each thread binds its own value. You can compare the ThreadLocal class to a box for global data storage, which can store the private data of each thread.

2. Class ThreadLocal has isolation, that is, each thread can store its own thread data without affecting each other, and what it gets is also the data stored by its own thread.

5、 Use of class inheritablethreadlocal

1. Inheritablethreadlocal class inherits from ThreadLocal class, so it has the characteristics of ThreadLocal class, but it is also a special ThreadLocal. Its particularity is that the value of inheritablethreadlocal variable will be automatically passed to all child threads, but ordinary ThreadLocal variable cannot; Moreover, by overriding the childvalue method in this class, the value of the child thread can be used as an arbitrary function of the value of the parent thread.

remarks:

(1) What is a child thread?

Included in thread = new thread (New threadstart (delegate {})); All of them are regarded as child threads. (personal understanding)

(2) What is the main thread?

Both the UI interface and the main function are the main thread. Except for "programs not included in the thread", they can be regarded as the main thread. (personal understanding)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>