The life cycle of threads in Java multithreaded programming

  • 2020-04-01 02:50:32
  • OfStack


//To start a thread
public void start( );
public void run( );
//Suspend and wake up threads
public void resume( ); //Not recommended
public void suspend( );//Not recommended
public static void sleep(long millis);
public static void sleep(long millis, int nanos);
//Termination of the thread
public void stop( );   //Not recommended
public void interrupt( );
//Get the thread state
public boolean isAlive( );
public boolean isInterrupted( );
public static boolean interrupted( );
//The join method
public void join( ) throws InterruptedException;

Create and run a thread

The thread does not execute the code in the run method immediately after it is created, but is in a wait state. When a Thread is in a waiting state, the methods of the Thread class can be used to set various properties of the Thread, such as the priority of the Thread, the name of the Thread, and the type of the Thread (setDaemon).
When the start method is called, the thread starts executing the code in the run method. The thread enters a running state. The isAlive method of the Thread class can be used to determine whether a Thread is running. When the thread is running, isAlive returns true, and when isAlive returns false, the thread may be in a wait state or a stop state. The following code illustrates the switch between creating, running, and stopping the thread, and outputs the corresponding isAlive return value.


package chapter2;
public class LifeCycle extends Thread
{
public void run()
{
int n = 0;
while ((++n) < 1000);
}

public static void main(String[] args) throws Exception
{
LifeCycle thread1 = new LifeCycle();
System.out.println("isAlive: " + thread1.isAlive());
thread1.start();
System.out.println("isAlive: " + thread1.isAlive());
thread1.join();  //Wait for thread1 to end before continuing execution
System.out.println("thread1 Has come to an end !");
System.out.println("isAlive: " + thread1.isAlive());
}
}

Note that the code above USES the join method, whose main function is to keep the program running until the thread's run method completes, which will be covered in a later article
The result of the above code:
IsAlive: false
IsAlive: true,
Thread1 is over!
IsAlive: false

Suspend and wake up threads

Once a thread starts executing the run method, it does not exit until the run method completes. But during a thread's execution, there are two ways to temporarily stop the thread from executing. The two methods are suspend and sleep. After suspending a thread with suspend, you can wake it up with the resume method. When sleep is used to make a thread sleep, the thread can only be in the ready state after a set time (after the thread sleep ends, the thread does not necessarily execute immediately, it just enters the ready state and waits for the system to schedule).
Although the suspend and resume can easily make the thread suspend and resume, but as a result of using these two methods may cause some unexpected things happen, therefore, these two methods is identified as deprecated (protest) markers, indicating that in JDK versions of these two methods can be deleted, so try not to use these two methods to manipulate threads. The following code demonstrates the use of the sleep, suspend, and resume methods.


package chapter2;
public class MyThread extends Thread
{
class SleepThread extends Thread
{
public void run()
{
try
{
sleep(2000);
}
catch (Exception e)
{
}
}
}
public void run()
{
while (true)
System.out.println(new java.util.Date().getTime());
}
public static void main(String[] args) throws Exception
{
MyThread thread = new MyThread();
SleepThread sleepThread = thread.new SleepThread();
sleepThread.start(); //Start running the thread sleepThread
sleepThread.join();  //Causes the thread sleepThread to be delayed by 2 seconds
thread.start();
boolean flag = false;
while (true)
{
sleep(5000);  //Delay the main thread by 5 seconds
flag = !flag;
if (flag)
thread.suspend(); 
else
thread.resume();
}
}
}

On the surface, using sleep and suspend produces similar results, but the sleep method is not the same as suspend. One of the biggest differences between them is that you can suspend another thread in one thread using the suspend method, as in the previous code where the thread is suspended on the main thread. Sleep, on the other hand, only works for the currently executing thread. In the above code, the sleepThread was made to sleep for 2 seconds and the main thread for 5 seconds, respectively. When using sleep, be careful that you cannot sleep another thread in one thread. For example, the thread.sleep(2000) method in the main method cannot make the thread sleep for 2 seconds, but can only make the main thread sleep for 2 seconds.
There are two things to note when using the sleep method:
1. The sleep method has two overloads, one of which can set not only milliseconds but also nanoseconds (1,000,000 nanoseconds = 1 millisecond). However, the Java virtual machine on most operating system platforms is not accurate to nanoseconds, so if you set the nanosecond for sleep, the Java virtual machine will take the nearest millisecond to that value.
2. You must use throws or try{... } catch {... }. Since the run method cannot use throws, only try{... } catch {... }. When interrupting a thread while it is asleep (discussed in 2.3.3), sleep throws an InterruptedException when the thread is interrupted. The definition of the sleep method is as follows:


public static void sleep(long millis)  throws InterruptedException
public static void sleep(long millis,  int nanos)  throws InterruptedException

Three ways to terminate a thread

There are three ways to terminate a thread.
1.   The exit flag is used to make the thread exit normally, that is, the thread terminates when the run method completes.
2.   Forcibly terminate a thread using the stop method (which is not recommended because stop, like suspend and resume, can have unpredictable results).
3.   Interrupt a thread with an interrupt method.
Use the exit flag to terminate the thread
When the run method is finished, the thread exits. But sometimes the run method never ends. Such as using threads to listen to client requests in a server-side program, or other tasks that require looping. In this case, it is common to put these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use the while(true){... } to handle. But the most straightforward way to make the while loop exit under a particular condition is to set a Boolean flag and control whether or not the while loop exits by setting the flag to true or false. An example of thread termination using the exit flag is given below.


package chapter2;
public class ThreadFlag extends Thread
{
public volatile boolean exit = false;
public void run()
{
while (!exit);
}
public static void main(String[] args) throws Exception
{
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(5000); //The main thread is delayed by 5 seconds
thread.exit = true;  //Terminate thread
thread.join();
System.out.println(" Thread to exit !");
}
}

In the above code, an exit flag exit is defined. When exit is true, the while loop exits, and the default value of exit is false. In defining exit, the Java keyword volatile is used to synchronize the exit, meaning that only one thread can modify the value of exit at a time.

2. Terminate the thread using the stop method

The stop method can be used to forcibly terminate a running or suspended thread. We can terminate the thread by using the following code:
Thread. Stop ();
Although you can terminate a thread using the code above, using the stop method can be dangerous, as it can cause unexpected results by suddenly turning off the computer instead of shutting it down as normal, so it is not recommended to use the stop method to terminate a thread.

Interrupt a thread
Using interrupt to terminate a thread can be divided into two cases:
(1) the thread is in a blocking state, such as using the sleep method.
(2) use while(! ()) {... } to determine whether the thread is interrupted.
Using interrupt in the first case, the sleep method throws an InterruptedException, and in the second case the thread simply exits. The following code demonstrates the use of interrupt in the first case.


package chapter2;
public class ThreadInterrupt extends Thread
{
public void run()
{
try
{
sleep(50000);  //50 seconds delay
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception
{
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println(" in 50 Press any key within seconds to interrupt the thread !");
System.in.read();
thread.interrupt();
thread.join();
System.out.println(" The thread has exited !");
}
}

The result of the above code is as follows:

 in 50 Press any key within seconds to interrupt the thread !
sleep interrupted
 The thread has exited !

After calling interrupt, the sleep method throws an exception and then outputs an error message: sleep interrupted.
Note: there are two methods in the Thread class that determine whether a Thread is terminated with interrupt. One is the static method interrupted() and the other is the non-static method isInterrupted(). The difference between the two methods is that interrupted is used to determine whether the current line isInterrupted, while isInterrupted can be used to determine whether other threads are interrupted. So, while (! IsInterrupted ()) can also be replaced by while (! Thread. Interrupted ()).


Related articles: