[Multi-thread summary]

Threads need to pay attention to:

1、

public final synchronized void join(long millis)    throws InterruptedException {  
        long base = System.currentTimeMillis();  
        long now = 0;  
  
        if (millis < 0) {  
            throw new IllegalArgumentException("timeout value is negative");  
        }  
          
        if (millis == 0) {  
            while (isAlive()) {  
                wait(0);  
            }  
        } else {  
            while (isAlive()) {  
                long delay = millis - now;  
                if (delay <= 0) {  
                    break;  
                }  
                wait(delay);  
                now = System.currentTimeMillis() - base;  
            }  
        }  
    }  

 

From the code point of view, if the thread is generated but not started yet, calling its join() method has no effect, and will continue to execute the Join method directly. The implementation is through wait (tip: the method provided by Object) . When the main thread calls t.join, the main thread will acquire the lock of the thread object t (wait means to get the lock of the object), and call the wait (waiting time) of the object until the object wakes up the main thread, such as after exiting . This means that when the main thread calls t.join, it must be able to obtain the lock of the thread t object

 

2. When interrupt() is called on a thread, if the thread is executing ordinary code, the thread will not throw InterruptedException at all . However, as soon as the thread enters wait()/sleep()/join(), an InterruptedException is thrown immediately. 

 

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 return directly in catch() {} to safely end the thread. 

 

Guess you like

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