Home  >  Article  >  Java  >  Detailed explanation of inter-thread communication in Java multithreading

Detailed explanation of inter-thread communication in Java multithreading

黄舟
黄舟Original
2017-09-14 10:51:422444browse

The following editor will bring you an article on java multi-thread programming learning (inter-thread communication). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

1. Overview

Threads are independent individuals in the operating system, but if these individuals do not go through Special processing cannot become a whole, and communication between threads is one of the necessary solutions to become a whole. It can be said that after threads are enabled to communicate, the interactivity between systems will be more powerful. While greatly improving CPU utilization, it will also enable programmers to effectively control and supervise the processing of each thread's tasks.

2. Wait/notify mechanism

1."wait/notify" mechanism: wait/notify mechanism, wait causes the thread to pause, and notify causes the suspended thread to continue running. Let’s use the interaction between a chef and a waiter to illustrate:

(1) The time when the waiter gets the dishes depends on the chef, so the waiter has a "wait" state.

(2) The chef places the dishes on the "dish delivery station", which is actually equivalent to a notification. Only then can the waiter get the dishes and hand them to the diners.

2. wait()

(1) Make the thread currently executing the code wait. The wait() method is a method of the Object class. This method is used to place the current thread into the "pre-execution queue" and stop execution at the line of code where wait() is located until a notification is received or interrupted.

(2) Before calling the wait() method, the thread must obtain the object-level lock of the object, that is, the wait() method can only be called in a synchronized method or synchronized block, otherwise an IllegalMonitorStateException exception will be thrown. (Belongs to a subclass of Runtime and does not require a try-catch statement to catch exceptions)

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

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

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

3. notify()

(1) is used to notify other threads that may be waiting for the object lock of the object. If there are multiple threads waiting, the thread planner randomly selects one of the threads in the wait state, issues a notify notification to it, and makes it wait to acquire the object lock of the object. (Note! What is mentioned here is waiting, that is, after executing the notify() method, the current thread will not release the object lock immediately, that is, the thread in the wait() state will not obtain the object lock immediately. The lock needs to be released after the code in the synchronized code block is executed! )

(2) must also be called in a synchronized method or synchronized block, that is, the thread must also obtain the object level of the object before calling. lock, otherwise IllegalMonitorStateException will be thrown.

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

4. notifyAll()

(1) can make all "all" threads in the waiting queue waiting for the same shared resource (that is, the same lock) start from Exit the waiting state and enter the runnable state.

5,

##6, Fake death: "Fake death "The phenomenon is actually that the thread enters the WAITING waiting state. If all threads enter the WAITING state, the program will no longer perform any functions and the entire project will be in a stopped state. The reason for this is: For example, in the case of multiple producers and multiple consumers, the "producer" may wake up the "producer", and the "consumer" may wake up the "consumer", which wakes up the same kind, causing the thread to continue to run. wait. How to solve this problem? Just change notify() to notifyAll() method, that is, wake up the heterogeneous classes together.

7, In Jave, pipe stream (pipeStream) is a special stream that can be used to directly transmit data in different threads. One thread sends data to the output pipe, and another thread reads data from the input pipe. By using pipes, communication between different threads is achieved without resorting to things like temporary files. Four classes are provided in the JDK to enable communication between threads, including byte streams (PipedOutputStream, PipedInputStream) and character streams (PipedWriter, PipedReader).


public class Run {
 public static void main(String[] args) {
  try {
   WriteData writeData = new WriteData();
   ReadData readData = new ReadData();
   PipedOutputStream outputStream = new PipedOutputStream();
   PipedInputStream inputStream = new PipedInputStream();
   
   outputStream.connect(inputStream);//使两个Stream之间产生通信链接,这样才可以将数据进行输入输出

   ThreadRead threadRead = new ThreadRead(readData, inputStream);
   threadRead.start();
   Thread.sleep(1000);
   ThreadWrite threadWrite = new ThreadWrite(writeData, outputStream);
   threadWrite.start();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}

3. Use of join method

1, In many cases, the main thread creates and starts a sub-thread. If a large amount of time-consuming calculations are to be performed in the sub-thread, the main thread will often end before the sub-thread ends. At this time, if the main thread wants to wait for the sub-thread to complete its execution before ending, for example, the sub-thread processes a piece of data, and the main thread wants to obtain the value in the data, it must use the join() method.

2. The function of join() is to wait for the thread to be destroyed, causing the current thread to block indefinitely. It waits for the join() thread 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 InterruptedException.

4. What is the difference between join and synchronized?

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

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

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

(1) join(long) is internally implemented using 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 join(long), the thread releases the lock and needs to compete with other threads for lock resources.

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

4. Use of ThreadLocal class

1. The sharing of variable values ​​can be in the form of public static variables. All threads use the same public static variable. How to solve this problem if we want each thread to have its own shared variables? The ThreadLocal class solves the problem of binding each thread to its own value. The ThreadLocal class can be compared to a box that stores global data. The box can store the private data of each thread.

2. The ThreadLocal class has isolation, that is, each thread can store the data of its own thread without affecting each other, and the data it retrieves is also the data stored by its own thread.

#5. Use of class InheritableThreadLocal

1, The InheritableThreadLocal class inherits from the ThreadLocal class, so it has the characteristics of the ThreadLocal class, but it is a special ThreadLocal. Its speciality is that the InheritableThreadLocal variable value will be automatically passed to all child threads. , but ordinary ThreadLocal variables cannot; moreover, by overriding the childValue method in this class, the value of the child thread can be used as the parent An arbitrary function of the thread value.

Remarks:

(1) What is a sub-thread?

Contained in Thread thread = new Thread(new ThreadStart(delegate{

})); 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

"programs not included in Thread" can be regarded as the main thread. (Personal understanding)

The above is the detailed content of Detailed explanation of inter-thread communication in Java multithreading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn