Multi-threaded notes

Theoretical summary: 

  • wait, notify and notifyAll can only be used in synchronous control methods or synchronous control blocks, while sleep can be used anywhere. So the biggest difference between sleep() and wait() methods is: sleep() keeps the object lock while sleeping, but still Occupy the lock; while wait() sleeps, release the object lock. But wait() and sleep() can interrupt the suspended state of the thread through the interrupt() method, so that the thread immediately throws InterruptedException (but this method is not recommended).

  • After the notify() method is executed, the current thread will not release the object lock immediately, and the thread in the wait state cannot acquire the object lock immediately. It has to wait until the notify() method thread finishes executing the program, that is, exits the synchronized code After the block, the current thread will release the lock. Only the thread in the wait state can acquire the object lock and execute the subsequent code of the wait() method. Summarize in one sentence: wait makes the thread stop running, and notify makes the stopped thread continue to execute.

  • When using notify() wait() mode, pay special attention to the program logic when the waiting condition of wait changes. In order to avoid abnormalities in the program (array corner mark out-of-bounds exceptions, etc.), use while(){ ...} instead of if(){ ...} for condition judgment.

  • Threads that call non-static synchronization methods in the same object will block each other. If it is a different object, each thread has its own object lock, and the threads do not interfere with each other.

  • Threads that call static synchronization methods in the same class will block each other, and they are all locked on the same Class object.

  • The static synchronization method and the non-static synchronization method will never block each other, because the static method is locked on the Class object, and the non-static method is locked on the object of the class.

  • interrupted() is a static method: the internal implementation is the isInterrupted() of the current thread that is called, and resets the interrupted state of the current thread; isInterrupted() is an instance method, which is the isInterrupted() of the thread represented by the object that called the method ), the interruption status of the current thread will not be reset.

  • The function of yield() is to make concessions. It allows the current thread to enter the "ready state" from the "running state", allowing other waiting threads with the same priority to obtain the right to execute; however, it does not guarantee that after the current thread calls yield(), other threads have the same priority Threads must be able to obtain the right to execute; it is also possible that the current thread has entered the "running state" to continue running!
  • The function of wait() is to let the current thread enter the "waiting (blocking) state" from the "running state" and at the same time release the synchronization lock. The function of yield() is to give in, and it will also let the current thread leave the "running state". The difference between them is:
    (01) wait() makes the thread enter the "waiting (blocking) state" from the "running state", while yield() makes the thread enter the "ready state" from the "running state".
    (02) wait() will release the synchronization lock of the object held by the thread, while the yield() method will not release the lock.
  • The daemon thread relies on the user thread. When the user thread exits, the daemon thread will also exit. A typical daemon thread is a garbage collection thread. The thread started by default is the user thread. The thread is set as a daemon thread by setDaemon(true). This function must be called before the thread is started (start() method), otherwise it will report java.lang.IllegalThreadStateException. A thread cannot become a daemon thread, but a user thread. The daemon thread should never access inherent resources, such as files and databases, because it will be interrupted at any time or even in the middle of an operation.

  • Use the InheritableThreadLocal class to let the child thread get the value from the parent thread. Value inherits the default value: Let the class inheriting InheritableThreadLocal override the initiaValue() method. Value inheritance and then modify: Let the class inheriting InheritableThreadLocal override the childValue() method.

  • ReentrantReadWriteLock read-write lock. Read and read shared; write and read mutual exclusion; read and write mutual exclusion; write and write mutual exclusion;   read lock: lock.readLock().lock(); write lock: lock.writeLock().lock();

  • Using the double check lock function (DCL), successfully solved the multi-threading problem encountered by the "lazy man mode". It not only guarantees the asynchronous execution without the need for synchronous code, but also guarantees the effect of singleton.

 

sleep() method:

  • sleep() causes the current thread to enter a stagnant state (blocks the current thread), and gives up the use of CUP. The purpose is to prevent the current thread from occupying the CPU resources obtained by the process alone, so as to leave a certain time for other threads to execute.

  •  sleep() is the Static (static) method of the Thread class; therefore, it cannot change the machine lock of the object, so when the Sleep() method is called in a Synchronized block, although the thread sleeps, the machine lock of the object does not exist. After being released, other threads cannot access the object (holding the object lock even if it is asleep).

  • After the sleep() sleep time expires, the thread may not be executed immediately, because other threads may be running and have not been scheduled to give up execution, unless this thread has a higher priority. 

 

wait() method:

  • The wait() method is a method in the Object class; when a thread executes to the wait() method, it enters a waiting pool associated with the object, and at the same time loses (releases) the machine lock of the object (temporarily loses the machine) Lock, the object lock needs to be returned after the wait(long timeout) timeout expires); other threads can access;
  • wait() uses notify or notifyAlll or specifies the sleep time to wake up the threads in the current waiting pool.
  • wiat() must be placed in the synchronized block, otherwise the "java.lang.IllegalMonitorStateException" exception will be thrown during the program runtime.

 

join() method:

 

The difference between sleep() and yield():

  • The difference between sleep() and yield()): sleep() causes the current thread to enter a stagnant state, so the thread executing sleep() will definitely not be executed within the specified time; yield() just makes the current thread back to Execution state, so the thread that executes yield() may be executed immediately after entering the executable state.
  • The sleep method makes the currently running thread sleep for a period of time and enters an inoperable state. The length of this period of time is set by the program. The yield method makes the current thread relinquish the CPU ownership, but the relinquish time cannot be set. . In fact, the yield() method corresponds to the following operations: first check whether there are currently threads with the same priority in the same runnable state, if so, transfer the CPU ownership to this thread, otherwise, continue to run the original thread. Therefore, the yield() method is called "yielding", which gives up the opportunity to run to other threads of the same priority.
  • In addition, the sleep method allows lower-priority threads to get a chance to run, but when the yield() method is executed, the current thread is still in a runnable state, so it is impossible to let a lower-priority thread get CPU ownership for a while . In a running system, if the higher-priority thread does not call the sleep method and is not blocked by I\O, then the lower-priority thread can only wait for all higher-priority threads to finish before they have a chance to run . 

 

 

Explanation of common thread terms:

Main thread: The thread generated by the JVM calling program main().
Current thread: This is a confusing concept. Generally refers to the process obtained through Thread.currentThread().
Background thread: refers to the thread that provides services for other threads, also known as the daemon thread. The garbage collection thread of the JVM is a background thread. The difference between a user thread and a daemon thread is that whether to wait for the main thread to end depends on the main thread to end the
foreground thread: refers to the thread that accepts the background thread service, in fact, the foreground and background threads are linked together, just like the puppet and the manipulator behind the scene relationship. The puppet is the foreground thread, and the manipulator behind the scenes is the background thread. The thread created by the foreground thread is also the foreground thread by default. The isDaemon() and setDaemon() methods can be used to determine and set whether a thread is a background thread.
Some common methods of thread class: 

  sleep(): Force a thread to sleep for N milliseconds. 
  isAlive(): Determine whether a thread is alive. 
  join(): Wait for the thread to terminate. 
  activeCount(): The number of active threads in the program. 
  enumerate(): Enumerate the threads in the program. 
       currentThread(): Get the current thread. 
  isDaemon(): Whether a thread is a daemon thread. 
  setDaemon(): Set a thread as a daemon thread. (The difference between user thread and daemon thread is whether to wait for the main thread to end depending on the end of the main thread) 
  setName(): Set a name for the thread. 
  wait(): Force a thread to wait. 
  notify(): Notify a thread to continue running. 
  setPriority(): Set the priority of a thread.

Blog reference: 

Java multi-threaded learning (hematemesis super detailed summary)

The difference between Synchronized (object lock) and Static Synchronized (class lock) 

The difference between synchronization method and synchronization code block 

Summary of the difference between interrupted() method and isInterrupted() method in Thread

Java multithreading series catalog (43 articles in total)

Guess you like

Origin blog.csdn.net/xiangwang2016/article/details/92794468