Java multithreading series_ Thread life cycle (4)

Like people, threads also experience four different states: start (wait), run, suspend and stop. These four states can be controlled by the methods in the thread class. The methods related to these four states are given below.

1、 Create and run threads

After the thread is established, it does not execute the code in the run method immediately, but is in a waiting state. When a thread is in the waiting state, you can set various properties of the thread through the method of thread class, such as thread priority (setpriority), thread name (setname), thread type (setdaemon), etc.

When the start method is called, the thread starts executing the code in the run method. The thread enters the running state. You can judge whether the thread is running through the isalive method of the thread class. When the thread is running, isalive returns true. When isalive returns false, the thread may be waiting or stopped. The following code demonstrates the switching between the three states of thread creation, run and stop, and outputs the corresponding isalive return value.

Note that the join method is used in the above code. The main function of this method is to ensure that the program will not continue to run until the run method of the thread is completed. This method will be introduced in later articles

The running result of the above code:

2、 Suspend and wake up threads

Once the thread starts executing the run method, it will not exit until the execution of the run method is completed. However, in the process of thread execution, there are two methods to make the thread temporarily stop execution. The two methods are suspend and sleep After suspending a thread with suspend, you can wake it up with the resume method. After using sleep to make the thread sleep, the thread can only be in the ready state after the set time (after the thread sleep ends, the thread does not necessarily execute immediately, but enters the ready state and waits for the system to schedule).

Although suspend and resume can easily suspend and wake up threads, the use of these two methods may cause some unexpected things to happen, These two methods are marked as deprecated, which indicates that these two methods may be deleted in future JDK versions, so try not to use these two methods to operate threads. The following code demonstrates the use of sleep, suspend and resume.

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
分享
二维码
< <上一篇
下一篇>>