Analysis of several cases of thread death in Java

The java thread conference ends in the following three ways, and is in a dead state after it ends

1. The execution of the run () or call () method is completed, and the thread ends normally;

2. The thread throws an uncapped exception or error;

3. Directly call the stop () method of the thread to end the thread;

Note: when the main thread ends, other threads are not affected and will not end with it. Once a child thread is started, it has the same status as the main thread and will not be affected by the end of the main thread.

In order to test whether a thread has died, you can call the isalive () method of the thread object. When the thread is in three states: ready, running and blocking, the method will return true; This method returns false when the thread is in both new and dead states.

Test 1 and 2 for thread death as follows.

The code of the main thread is as follows:

Test 1: after the thread ends normally, isalive() returns false

Write thread execution code for normal end of thread:

The output results of the two threads are as follows. After the normal execution of the child thread, use thread Isalive() returns false.

Test 2: after the child thread throws an exception, the thread's isalive() returns false

Modify the code of the child thread and add an exception throw:

Execute again and observe the output:

It can be seen that after an exception is thrown, the child thread terminates directly and becomes a flag state;

summary

After the thread ends normally or the thread throws an uncapped exception, the thread becomes dead. Use the isalive() function to return false. Well, the above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>