Java Multithreading (4)----Four states of a thread

Source: Internet
Author: User
Tags set time

As with people, threads also have to go through four different states of starting (waiting), running, suspending, and stopping. These four states can be controlled through the methods in the thread class. The thread class and the four state-related methods are given below.

1  //start thread 2 public void     start (), 3 public     void Run (), 4  5     //Suspend and wake thread 6 public     void Resume (); 
   //does not recommend the use of 7 public     void Suspend ();    Using 8 public     static void sleep (long Millis) is not recommended, 9 public     static void sleep (long millis, int nanos);     Terminating thread     , public void Stop ();       It is not recommended to use the public     Void Interrupt ();     \ n/Get the thread state of the public     Boolean isAlive ();     Nterrupted (); public     static Boolean interrupted ();     //Join method public     void Join () throws Interrup Tedexception;

One, create and run a thread

The thread does not immediately execute the code in the Run method after it is established, but is in a wait state. When a thread is in a wait state, it is possible to set threads with different properties, such as thread priority (setpriority), thread name (setName), and thread type (Setdaemon), by means of the thread class.

When the Start method is called, the thread starts executing the code in the Run method. The thread goes into a running state. You can determine whether a thread is running by using the IsAlive method of the thread class. When the thread is running, IsAlive returns True, and when IsAlive returns FALSE, the thread may be in a wait state or it may be in a stopped state. The following code shows the switch between the creation, running, and stopping of three states for a thread, and outputs the corresponding IsAlive return value.

1 package chapter2;  2  3 public class LifeCycle extends Thread 4 {5 "public     Void" Run () 6     {7         int n = 0; 8 while         (++n) < );         9     }10      public     static void Main (string[] args) throws Exception12     {         LifeCycle thread1 = new LifeCycle ();         System.out.println ("isAlive:" + thread1.isalive ());         System.out.println ("isAlive:" + thread1.isalive ());         Thread1.join ();  Wait until the thread thread1 is finished before continuing with         System.out.println ("Thread1 is over!");         System.out.println ("isAlive:" + thread1.isalive ());     }21}

Note that the Join method is used in the code above, and the main function of this method is to ensure that the program continues to run after the thread's Run method is completed, which is described in a later article

The running result of the above code:

IsAlive:falseisAlive:truethread1 has ended!isalive:false

Second, suspend and wake-up threads

Once the thread starts executing the Run method, it will continue until this run method executes the line friend exits. However, in the course of thread execution, there are two ways to make threads temporarily stop executing. These two methods are suspend and sleep. After you use suspend to suspend a thread, you can wake the thread through the Resume method. While sleep causes a thread to hibernate, the thread is ready only after a set time (the thread does not necessarily execute immediately after the end of the threads hibernation, but is in a ready state, waiting for the system to dispatch).

Although suspend and resume can easily suspend and wake threads, these two methods are identified as deprecated (protest) tokens because using these two methods can cause unforeseen events, which indicates that both methods may be removed in later JDK versions , so try not to use these two methods to manipulate threads. The following code demonstrates the use of the sleep, suspend, and resume three methods.

 1 package chapter2;          2 3 public class MyThread extends thread 4 {5 class Sleepthread extends thread 6 {7 public void run () 8  {9 Try10 {one sleep (each);}13 catch (Exception             e) {}16}17}18 public void Run (), {21 while (true) System.out.println (New Java.util.Date (). GetTime ());}23 public static void Main (string[] args) throws Excepti         ON24 {MyThread thread = new MyThread (); Sleepthread sleepthread = Thread.new sleepthread (); 27 Sleepthread.start ();  Start running thread sleepThread28 sleepthread.join ();             Causes thread sleepthread to delay 2 seconds Thread.Start (); Boolean flag = False;31 while (true) 32 {33  Sleep (5000); Delay the main thread by 5 seconds. Flag =!flag;35 if (flag) thread.suspend (); Panax Notoginseng else38 Thread.resUme (); 39}40}41} 

On the surface, the effects of using sleep and suspend are similar, 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 through the Suspend method, such as the thread thread that hangs in the main thread in the code above. And sleep only works on threads that are currently executing. In the above code, the Sleepthread and the main thread are respectively dormant for 2 seconds and 5 seconds. When using sleep, be aware that you cannot hibernate another thread in one thread. The use of the Thread.Sleep (2000) method in the main method does not allow the thread thread to hibernate for 2 seconds, but only causes the main thread to hibernate for 2 seconds.

There are two points to note when using the Sleep method:

1. The sleep method has two overloaded forms, where one of the overloaded forms can be set not only in milliseconds, but also in nanoseconds (1,000,000 nanoseconds equals 1 milliseconds). However, the Java virtual machines on most operating system platforms are not accurate to nanoseconds, so if you set the nanosecond to sleep, the Java virtual machine will take the milliseconds closest to this value.

2. You must use throws or try{when using the Sleep method ...} Catch{...}. Because the Run method cannot use throws, you can only use try{...} Catch{...}. Sleep throws a Interruptedexception exception during thread hibernation, using the interrupt method (which is discussed in 2.3.3) when the thread is disconnected. The sleep method is defined as follows:

1 public static void sleep (long Millis)  throws InterruptedException2 public static void sleep (long millis,  int nan OS)  throws Interruptedexception

Iii. three ways to terminate a thread

There are three ways to make a terminating thread.

1. Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the Run method completes.

2. Use the Stop method to forcibly terminate the thread (this method is not recommended because stop and suspend, resume, can also cause unpredictable results).

3. Use the interrupt method to break the thread.

1. Terminating a thread with an exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never finished. Use threads to listen for client requests in a server-side program, or other tasks that require cyclic processing. In this case, it is common to place these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use while (True) {...} To deal with. However, the most straightforward way to make a while loop exit under a particular condition is to set a Boolean flag and control whether the while loop exits by setting this flag to true or false. An example of terminating a thread with an exit flag is given below.

1 package chapter2; 2  3 public class Threadflag extends Thread 4 {5 publicly     volatile Boolean exit = FALSE; 6  7 public     void Run () 8     {9         while (!exit),     }11 public     static void Main (string[] args) throws Exception12     {         Threadflag thread = new Threadflag ();         Thread.Start ();         sleep (5000);//main thread delay 5 sec.         thread.exit = true;  //terminating thread Thread17         thread.join ();         System.out.println ("Thread exits!");     }20}

An exit flag is defined in the preceding code exit, and when Exit is true, the while loop exits, The default value for Exit is false. When you define exit, a Java keyword, volatile, is used to synchronize exit, meaning that only one thread can modify the value of exit at the same time.

2. Terminating a thread by using the Stop method

Use the Stop method to forcibly terminate a running or suspended thread. We can use the following code to terminate the thread:

1 thread.stop ();

Although using the above code can terminate a thread, using the Stop method is dangerous, just like suddenly shutting down the computer, rather than shutting down as a normal program, it is not recommended to use the Stop method to terminate the thread.

3. Terminating a thread using the interrupt method

Using the interrupt method to end a thread can be divided into two situations:

(1) The thread is in a blocked state, such as using the Sleep method.

(2) Use while (! Isinterrupted ()) {...} To determine if a thread has been interrupted.

In the first case, using the interrupt method, the sleep method throws a Interruptedexception exception, and in the second case the thread exits directly. The following code demonstrates the use of the interrupt method in the first case.

1 package chapter2; 2  3 public class Threadinterrupt extends Thread 4 {5 public     void Run () 6     {7         try 8         {9             sleep (5000 0);  Delay 50 seconds         }11         catch (interruptedexception e)         {             System.out.println (e.getmessage ());     }16 public     static void Main (string[] args) throws Exception17     {*         thread thread = new Threadinterrupt ();         Thread.Start ()         System.out.println ("Press any key within 50 seconds to break the thread!");         System.in.read ();         thread.interrupt ();         thread.join ();         System.out.println ("Thread has exited!");     }26}

The result of the above code is as follows:

Press any key within 50 seconds to break the thread! Sleep interrupted thread has exited!

After calling the interrupt method, the Sleep method throws an exception and then outputs the error message: Sleep interrupted.

Note: There are two methods in the thread class to determine whether a thread is terminated through the interrupt method. One is static method interrupted (), a non-static method isinterrupted (), the difference between the two methods is interrupted to determine whether the current line is interrupted, and isinterrupted can be used to determine whether other threads are interrupted. So while (! Isinterrupted ()) can also be replaced by while (! Thread.interrupted ()).

Original: http://java.chinaitlab.com/line/778850.html

Java Multithreading (4)----Four states of a thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.