Java multi-thread Series 7-Stop thread, java multi-thread 7-Thread

Source: Internet
Author: User

Java multi-thread Series 7-Stop thread, java multi-thread 7-Thread

This article mainly summarizes how to stop a thread in java.

There are three methods in java to terminate a running thread:

1. Use Exit flag

2. Use the stop method to forcibly terminate the thread, but it is not recommended because the stop method is outdated like suspend and resume.

3. Interrupt the thread using the interrup Method

Thread that cannot be stopped

In this example, the interrupt method is used to stop the process. The result is as follows:

public class MyThread extends Thread {    @Override    public void run() {        super.run();        for (int i = 0; i < 1234; i++) {            System.out.println("i=" + (i + 1));        }    }}public class Run {    public static void main(String[] args) {        try {            MyThread thread = new MyThread();            thread.start();            Thread.sleep(2000);            thread.interrupt();                                } catch (InterruptedException e) {            System.out.println("main catch");            e.printStackTrace();        }    }}

It can be seen that the thread has not stopped

Determines whether the thread is in the stopped status.

In the java SDK, the Thread. java class provides two methods:

(1) this. interrupted (): test whether the current thread has been interrupted

(2) this. isInterrupted (): test whether the thread has been interrupted

First take a look At interrupted ()

Practical Verification:

Public class MyThread extends Thread {@ Override public void run () {super. run (); for (int I = 0; I <10000; I ++) {System. out. println ("I =" + (I + 1) ;}} public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 1000); thread. interrupt (); System. out. println ("Stop 1? = "+ Thread. interrupted (); System. out. println (" Stop 2? = "+ Thread. interrupted ();} catch (InterruptedException e) {System. out. println ("main catch"); e. printStackTrace ();} System. out. println ("end! ");}}

The running result is as follows:

.......................

I = 9998.
I = 9999.
I = 10000.
Stop 1? = False
Stop 2? = False
End!

Because interrupted is the current thread for testing, the current thread is main and has not been interrupted, so two false values are returned.

Modify the Code:

Public class Run {public static void main (String [] args) {Thread. currentThread (). interrupt (); System. out. println ("Stop 1? = "+ Thread. interrupted (); System. out. println (" Stop 2? = "+ Thread. interrupted (); System. out. println (" end! ");}}

The following information is returned:

Stop 1? = True
Stop 2? = False
End!

The interrupted method can be used to clear the status, so false is returned for the second time.

Let's take a look at the isInterrupted () method.

Public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 1000); thread. interrupt (); System. out. println ("Stop 1? = "+ Thread. isInterrupted (); System. out. println (" Stop 2? = "+ Thread. isInterrupted ();} catch (InterruptedException e) {System. out. println ("main catch"); e. printStackTrace ();} System. out. println ("end! ");}}

Running result:

I = 123367.
I = 123368.
Stop 1? = True
Stop 2? = True
I = 123369.
I = 123370.
I = 123371.
I = 123372.

Summary:

(1) this. interrupted (): checks whether the current thread has been interrupted. After execution, it can clear the status flag to false.

(2) this. isInterrupted (): test whether the thread has been interrupted, but the status flag is not cleared.

Thread that can be stopped-exception Method

You can use the for statement in the thread to determine whether the thread is in the stopped status. If the thread is in the stopped status, the subsequent code will not run any more.

Public class MyThread extends Thread {@ Override public void run () {super. run (); try {for (int I = 0; I <500000; I ++) {if (this. interrupted () {System. out. println ("it's already stopped. I want to quit! "); Throw new InterruptedException ();} System. out. println ("I =" + (I + 1);} System. out. println ("I am under for");} catch (InterruptedException e) {System. out. println ("into MyThread. catch in the java class run method! "); E. printStackTrace () ;}} public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 2000); thread. interrupt ();} catch (InterruptedException e) {System. out. println ("main catch"); e. printStackTrace ();} System. out. println ("end! ");}}
Stop in sleep

What is the effect of stopping a thread in sleep state?

Public class MyThread extends Thread {@ Override public void run () {super. run (); try {System. out. println ("run begin"); Thread. sleep (1, 200000); System. out. println ("run end");} catch (InterruptedException e) {System. out. println ("stopped in sleep! Go to catch! "+ This. isInterrupted (); e. printStackTrace () ;}} public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 200); thread. interrupt ();} catch (InterruptedException e) {System. out. println ("main catch"); e. printStackTrace ();} System. out. println ("end! ");}}

Running result:

Run begin
End!
Stopped in sleep! Go to catch! False
Java. lang. InterruptedException: sleep interrupted
At java. lang. Thread. sleep (Native Method)
At com. wuyudong. test1.MyThread. run (MyThread. java: 9)

The result indicates that if a thread is stopped in sleep state, the catch statement is entered and the Stop State value is cleared to false.

Next, perform the opposite operation and modify it:

Public class MyThread extends Thread {@ Override public void run () {super. run (); try {for (int I = 0; I <100000; I ++) {System. out. println ("I =" + (I + 1);} System. out. println ("run begin"); Thread. sleep (1, 200000); System. out. println ("run end");} catch (InterruptedException e) {System. out. println ("stop first, then sleep! Go to catch! "); E. printStackTrace () ;}} public class Run {public static void main (String [] args) {MyThread thread = new MyThread (); thread. start (); thread. interrupt (); System. out. println ("end! ");}}

The running result is as follows:

I = 100000.
Run begin
Stop first, and then run into sleep! Go to catch!
Java. lang. InterruptedException: sleep interrupted
At java. lang. Thread. sleep (Native Method)
At com. wuyudong. test1.MyThread. run (MyThread. java: 12)

Thread that can be stopped-force stop

It is very violent to stop a thread using the stop method.

Public class MyThread extends Thread {private int I = 0; @ Override public void run () {super. run (); try {while (true) {I ++; System. out. println ("I =" + I); Thread. sleep (1000) ;}} catch (InterruptedException e) {System. out. println ("stop first, then sleep! Go to catch! "); E. printStackTrace () ;}} public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 8000); thread. stop ();} catch (Exception e) {e. printStackTrace ();}}}

The running result is as follows:

I = 1
I = 2
I = 3
I = 4
I = 5
I = 6
I = 7
I = 8

Method stop and exception

A java. lang. ThreadDeath exception is thrown when the stop method is called. However, this exception usually does not need to be explicitly captured.

Public class MyThread extends Thread {private int I = 0; @ Override public void run () {super. run (); try {while (true) {I ++; System. out. println ("I =" + I); Thread. sleep (1000) ;}} catch (InterruptedException e) {System. out. println ("stop first, then sleep! Go to catch! "); E. printStackTrace () ;}} public class Run {public static void main (String [] args) {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 8000); thread. stop ();} catch (Exception e) {e. printStackTrace ();}}}
Use return to stop a thread

The method interrupt and return can be used together to stop the thread.

Public class MyThread extends Thread {private int I = 0; @ Override public void run () {super. run (); while (true) {if (this. isInterrupted () {System. out. println ("stopped! "); Return;} System. out. println ("timer =" + System. currentTimeMillis () ;}} public class Run {public static void main (String [] args) throws InterruptedException {try {MyThread thread = new MyThread (); thread. start (); Thread. sleep (1, 2000); thread. interrupt ();} catch (Exception e) {e. printStackTrace ();}}}

The running result is as follows:

Timers = 1452841019023
Timers = 1452841019023
Timers = 1452841019023
Timers = 1452841019023
Stopped!

 

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.