Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - If multithreading is used in a JAVA program, the start method will make all threads concurrent. How to avoid the phenomenon that the program is finished and the thread is not finished?
If multithreading is used in a JAVA program, the start method will make all threads concurrent. How to avoid the phenomenon that the program is finished and the thread is not finished?
Why the recommended method is described in the thread. Stop, thread. Pause and thread. Resume has been discarded? ",it is suggested to use the following methods to stop the thread:

Private mutable thread blinker

Public invalid site () {

blinker = null

}

Public invalid operation () {

thread this thread = thread . current thread();

while (blinker == thisThread) {

Try {

ThisThread.sleep (interval);

} catch (InterruptedException e){

}

repaint();

}

}

See/docs/books/jls/second _ edition/html/classes.doc.html # 36930 for the reason of using volatile keyword.

When a thread is not running, it is not running if it is:

When the sleep method is called.

When the wait method is called.

When blocked by I/O, it may be a file or a network, etc.

When the thread is in the above state, the method described above cannot be used. At this time, we can use interrupt () to break the blocking situation, for example:

Public invalid site () {

Thread tmpBlinker = blinker

blinker = null

if (tmpBlinker! = null) {

tmpblinker . interrupt();

}

} InterruptedException will be thrown when calling interrupt (), so you can catch this exception in the run method and let the thread exit safely:

Try {

....

wait();

} catch(interrupted exception iex){

Throw new runtime exception ("interrupted", iex);

}

Source reference:/yedeqixian/item/fe89dd3e4bbf215180f1a761