Detailed explanation of java thread basic methods

First, the thread state transition

1. New state (New): A thread object is newly created.
2. Ready state (Runnable): After the thread object is created, other threads call the start() method of the object. Threads in this state are in the runnable thread pool and become runnable, waiting to acquire the right to use the CPU.
3. Running state (Running): The thread in the ready state acquires the CPU and executes the program code.
4. Blocked state (Blocked): The blocked state is that the thread gives up the right to use the CPU for some reason and temporarily stops running. Until the thread enters the ready state, there is no chance to go to the running state. There are three types of blocking:
(1) Waiting for blocking: The running thread executes the wait() method, and the JVM will put the thread into the waiting pool. (wait will release the held lock)
(2) Synchronization blocking: When the running thread acquires the synchronization lock of the object, if the synchronization lock is occupied by another thread, the JVM will put the thread into the lock pool.
(3) Other blocking: When the running thread executes the sleep() or join() method, or issues an I/O request, the JVM will place the thread in a blocked state. When the sleep() state times out, join() waits for the thread to terminate or times out, or when the I/O processing is complete, the thread re-enters the ready state. (Note that sleep will not release the held lock)
5. Dead state (Dead): The thread finishes executing or exits the run() method due to an exception, and the thread ends its life cycle.
 
2. Thread scheduling
2. Thread sleep: The Thread.sleep(long millis) method turns the thread into a blocked state. The millis parameter sets the sleep time in milliseconds. When the sleep is over, it turns to the ready (Runnable) state. sleep() platform has good portability.
 
3. Thread waiting: The wait() method in the Object class causes the current thread to wait until other threads call the notify() method or notifyAll() wake-up method of this object. These two wake-up methods are also methods in the Object class, and their behavior is equivalent to calling wait(0).
 
4. Thread yield: The Thread.yield() method suspends the currently executing thread object and gives the execution opportunity to a thread of the same or higher priority.
 
5. Thread join: join() method, waiting for other threads to terminate. If the join() method of another thread is called in the current thread, the current thread will enter the blocking state until the other process finishes running, and the current thread will change from the blocking state to the ready state.
 
6. Thread wakeup: The notify() method in the Object class wakes up a single thread waiting on this object monitor. If all threads are waiting on this object, one of them will be chosen to wake up. The choice is arbitrary and happens when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Execution of the awakened thread cannot continue until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual way with all other threads actively synchronizing on this object; for example, the awakened thread has no reliable privilege or disadvantage in being the next thread to lock this object. A similar method also has a notifyAll(), which wakes up all threads waiting on this object's monitor.
 Note: The two methods of suspend() and resume() in Thread have been abolished in JDK1.5 and will no longer be introduced. Because of the tendency to deadlock.
 
3. Description of common functions
①sleep(long millis): Sleep the currently executing thread within the specified number of milliseconds (suspend execution, sleep will not release the lock held );

②t.join(): Refers to waiting for t thread to complete execution, join is Thread A method of the class, which is called directly after starting the thread, that is, the function of join() is: "waiting for the thread to terminate", what needs to be understood here is that the thread refers to the main thread waiting for the termination of the child thread. That is, the code after the child thread calls the join() method can only be executed after the child thread ends.
In many cases, the main thread generates and starts sub-threads. If a large number of time-consuming operations are to be performed in the sub-threads, the main thread usually ends before the sub-threads. However, if the main thread finishes other transactions, it needs to use To the processing result of the child thread, that is, the main thread needs to wait for the child thread to complete the execution before ending. At this time, the join() method is used.
③yield(): Pause the currently executing thread object and execute other threads.
         The function of the Thread.yield() method is to suspend the currently executing thread object and execute other threads.
          What yield() should do is bring the currently running thread back into a runnable state to allow other threads of the same priority to get a chance to run. Therefore, the purpose of using yield() is to allow appropriate round-robin execution between threads of the same priority. However, there is no guarantee that yield() will yield in practice, because the yielding thread may still be re-selected by the thread scheduler.
Conclusion: yield() never caused the thread to go to wait/sleep/block state. In most cases, yield() will cause the thread to go from the running state to the runnable state, but it may have no effect.
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 return to the executable state, so the thread executing yield() may be executed again immediately after entering the executable state.
        The sleep method makes the currently running thread sleepy 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 give up the CPU ownership, but the given time cannot be set. . In fact, the yield() method corresponds to the following operations: first check whether there are currently threads of the same priority in the same runnable state, if so, give the CPU ownership to this thread, otherwise, continue to run the original thread. So the yield() method is called "backing off", it gives the running opportunity to other threads of the same priority.
       In addition, the sleep method allows lower priority threads to get the running opportunity, but when the yield() method is executed, the current thread is still It is in a runnable state, so it is impossible to give a lower priority thread some time to take the CPU. 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 . 
④setPriority(): Change the priority of the thread.

    MIN_PRIORITY = 1
       NORM_PRIORITY = 5
           MAX_PRIORITY = 10

Usage: The larger the value set, the more priority to be executed;
Thread4 t1 = new Thread4("t1");
Thread4 t2 = new Thread4("t2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
⑤interrupt(): Don't think that it interrupts a thread, it just sends an interrupt signal to the thread, so that the thread can throw an exception when it waits infinitely (such as deadlock), thereby ending the thread; but if you eat this Exception, then this thread will not be interrupted!

⑥wait()

Obj.wait(), and Obj.notify() must be used together with synchronized(Obj), that is, wait, and notify is to operate on the Obj lock that has been acquired, from a grammatical point of view, it is Obj.wait(), Obj.notify must be inside a synchronized(Obj){...} block . Functionally, wait means that the thread actively releases the object lock after acquiring the object lock, and the thread sleeps at the same time. Until another thread calls the object's notify() to wake up the thread, it can continue to acquire the object lock and continue to execute. The corresponding notify() is the wake-up operation on the object lock. But one thing to note is that after the notify() call, the object lock is not released immediately, but after the execution of the corresponding synchronized(){} statement block ends, after the lock is automatically released, the JVM will wait() the object lock Randomly select a thread among the threads, give it an object lock, wake up the thread, and continue to execute. This provides synchronization and wake-up operations between threads. Both Thread.sleep() and Object.wait() can suspend the current thread and release the CPU control. The main difference is that Object.wait() releases the control of the object lock while releasing the CPU.

The difference between wait and sleep has in
common: 

1. They are both in a multi-threaded environment, and they can block the specified number of milliseconds at the call of the program and return. 
2. Both wait() and sleep() can interrupt the suspended state of the thread through the interrupt() method, so that the thread immediately throws InterruptedException. 
   If thread A wants to end thread B immediately, it can call the interrupt method on the Thread instance corresponding to thread B. If thread B is waiting/sleep/join at the moment, thread B will throw InterruptedException immediately, and the thread can be safely terminated by returning directly in catch() {}. 
   It should be noted that InterruptedException is thrown internally by the thread itself, not by the interrupt() method. When interrupt() is called on a thread that is executing normal code, the thread never throws an InterruptedException. However, as soon as the thread enters wait()/sleep()/join(), an InterruptedException is thrown immediately. 
Differences: 
1. Thread class methods: sleep(), yield(), etc. 
   Object methods: wait() and notify(), etc. 
2. Each object has a lock to control synchronous access. The Synchronized keyword can interact with the object's lock to achieve thread synchronization. 
   The sleep method does not release the lock, while the wait method releases the lock so that other threads can use the synchronized control block or method. 
3. wait, notify and notifyAll can only be used in synchronous control methods or synchronous control blocks, while sleep can be used anywhere 
4. sleep must catch exceptions, while wait, notify and notifyAll do not need to catch exceptions
so sleep() and wait The biggest difference between () method is:
    when sleep() sleeps, it keeps the object lock and still holds the lock;
    while wait() sleeps, it releases the object lock.
  However, both 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).
The sleep() method
sleep() makes the current thread enter a stagnant state (blocks the current thread), and gives up the use of the CPU. 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. Opportunity;
   sleep() is the 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 change. The wood has not been released, and other threads cannot access the object (the object lock is held even if it is asleep).
  After the sleep() sleep time expires, the thread may not execute immediately because other threads may be running and not scheduled to give up unless the thread has a higher priority. 
wait() method
The wait() method is a method in the Object class; when a thread executes the wait() method, it enters a waiting pool related to the object, and at the same time loses (releases) the object's machine lock (temporarily loses the machine lock). lock, the object lock needs to be returned after the wait (long timeout) timeout period); other threads can access;
  wait() uses notify or notifyAll or the specified sleep time to wake up the threads in the current waiting pool.
  wiat() must be placed in a synchronized block, otherwise a "java.lang.IllegalMonitorStateException" will be thrown at program runtime.
4. Some common methods of thread class: 
  sleep(): Force a thread to sleep for N milliseconds. 
  isAlive(): Determines whether a thread is alive. 
  join(): Wait for the thread to terminate. 
  activeCount(): The number of active threads in the program. 
  enumerate(): Enumerates threads in a program. 
    currentThread(): Get the current thread. 
  isDaemon(): Whether a thread is a daemon thread. 
  setDaemon(): Sets a thread as a daemon thread. (The difference between user threads and daemon threads 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(): Forces a thread to wait. 
  notify(): Notifies a thread to continue running. 
  setPriority(): Sets the priority of a thread.
Five, thread synchronization
1. There are two scopes of the synchronized keyword: 
1) Within an object instance, synchronized aMethod(){} can prevent multiple threads from accessing the synchronized method of this object at the same time (if an object has multiple synchronized methods, as long as A thread accesses one of the synchronized methods, other threads cannot access any of the synchronized methods in this object at the same time). At this time, the synchronized methods of different object instances do not interfere with each other. That is to say, other threads can still access synchronized methods in another object instance of the same class at the same time; 
2) is the scope of a class, synchronized static aStaticMethod{} prevents multiple threads from accessing synchronized static methods in this class at the same time. It works on all object instances of the class. 

2. In addition to using the synchronized keyword before the method, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block are mutually exclusive access. The usage is: synchronized(this){/*block*/}, its scope is the current object; 

3. The synchronized keyword cannot be inherited, that is, the method synchronized f(){} of the base class is inherited The class is not automatically synchronized f(){}, but becomes f(){}. Inheriting a class requires you to explicitly specify one of its methods as a synchronized method; 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324971377&siteId=291194637