Use of the lifecycle of Java thread threads _java

Source: Internet
Author: User
Tags set time thread class volatile

As with people living in sickness and death, threads also experience starting (waiting), running, suspending, and stopping four of different states. These four states can be controlled by methods in the thread class. The thread class and the four state-related methods are given below.

Copy Code code as follows:

Start thread
public void start ();
public void run ();

Suspend and wake up threads
public void resume (); Use not recommended
public void suspend (); Use not recommended
public static void sleep (long millis);
public static void sleep (long millis, int nanos);

Terminating a thread
public void Stop (); Use not recommended
public void interrupt ();

Get thread State
public boolean isAlive ();
public boolean isinterrupted ();
public static Boolean interrupted ();

Join method
public void Join () throws interruptedexception;

First, create and run the thread

Instead of executing the code in the Run method immediately after it is established, the thread is in the waiting state. When a thread is in a waiting state, you can use the method of the thread class to set the thread's not various properties, such as the thread's priority (setpriority), the thread name (SetName), and the type of thread (Setdaemon).

When the Start method is called, the thread starts executing the code in the Run method. The thread enters the 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, it is possible that the thread is either in a waiting state or in a stopped state. The following code shows a switch between three states where a thread is created, run, and stopped, and outputs the corresponding IsAlive return value.

Copy Code code as follows:

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 until the thread thread1 ends before continuing
System.out.println ("Thread1 is over!");
System.out.println ("isAlive:" + thread1.isalive ());
}
}

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

The running result of the above code:

Copy Code code as follows:

Isalive:false
Isalive:true
Thread1 is over!
Isalive:false

Second, suspend and wake up the thread

Once the thread starts executing the Run method, it will go on to the Run method to complete the line Cheng exit. However, in the process of thread execution, two methods can be used to temporarily stop the thread from executing. These two methods are suspend and sleep. After you suspend a thread using suspend, you can wake the thread through the Resume method. With sleep, which causes the thread to hibernate, it can only be ready after the set time (after the thread hibernation is finished, threads do not necessarily execute immediately, just enter the ready state and wait 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 they can cause unpredictable things to happen, indicating that the two methods may be removed in later versions of JDK , so try not to use these two methods to manipulate threads. The following code demonstrates the use of three methods for sleep, suspend, and resume.

Copy Code code as follows:

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 thread Sleepthread
Sleepthread.join (); Causes thread sleepthread to delay 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 effects, But the sleep method does not equate to suspend. One of the biggest differences between them is that you can suspend another thread in one thread by suspend method, such as the thread thread in the main thread in the code above. Sleep only works on threads that are currently executing. In the code above, the Sleepthread and main threads were dormant for 2 seconds and 5 seconds. When you use sleep, be aware that you cannot hibernate another thread in one thread. Using the Thread.Sleep (2000) method in the main method does not allow the thread thread to hibernate for 2 seconds, but can only cause the main thread to hibernate for 2 seconds.

There are two points to be aware of when using the Sleep method:

1. The sleep method has two overloaded forms, one of which can be set to not only milliseconds but also 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 a nanosecond for sleep, the Java virtual machine takes milliseconds closest to that value.

2. When using the Sleep method, you must use throws or try{...} Catch{...}. Because the Run method cannot use throws, you can only use try{...} Catch{...}. When a thread is dormant, sleep throws a Interruptedexception exception using the Interrupt method (this method will be discussed in 2.3.3). The sleep method is defined as follows:

Copy Code code as follows:

1 public static void sleep (long Millis) throws Interruptedexception
2 public static void sleep (long millis, int nanos) throws Interruptedexception

Iii. three ways to terminate a thread

There are three ways to terminate the 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 force a thread to terminate (this method is not recommended because it can also occur unpredictable results, as with suspend, resume).

3. Use the interrupt method to disconnect threads.

1. Terminate thread with Exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never going to end. such as using threads in a server-side program to listen for client requests, or other tasks that need to be cycled. In this case, you typically 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 deal with. But the most straightforward way to get the while loop to exit under a certain condition is to set a Boolean flag and control whether the while loop exits by setting the flag to true or false. An example of terminating a thread with an exit flag is given below.

Copy Code code as follows:

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); Main thread delay 5 seconds
Thread.exit = true; Terminating thread Threads
Thread.Join ();
SYSTEM.OUT.PRINTLN ("Thread exit!");
}
}

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

2. Terminate a thread using the Stop method

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

Copy Code code as follows:

1 thread.stop ();

Although using the above code to terminate a thread, it is dangerous to use the Stop method, which may produce unpredictable results when you suddenly turn off the computer instead of shutting down the normal program, and therefore it is not recommended that you terminate the thread with the Stop method.

3. Terminating a thread using the interrupt method

Using the interrupt method to end threads can be divided into two scenarios:

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

(2) Use while (! Isinterrupted ()) {...} To determine if the thread was 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.

Copy Code code as follows:

Package chapter2;

public class Threadinterrupt extends Thread
{
public void Run ()
{
Try
{
Sleep (50000); Delay 50 seconds
}
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 ("Press any key within 50 seconds to disconnect thread!");
System.in.read ();
Thread.Interrupt ();
Thread.Join ();
SYSTEM.OUT.PRINTLN ("Thread has exited!");
}
}

The results of the above code run as follows:
Copy Code code as follows:

Press any key within 50 seconds to disconnect the thread!

Sleep interrupted
The thread has exited!


After the interrupt method is invoked, the sleep method throws an exception and then prints an error message: Sleep interrupted.

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

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.