Thread stop in Java (4)

Source: Internet
Author: User

When the Java thread is stopped and the thread is enabled, sometimes we need to stop the thread execution. Generally, there are two types of stop:

1: Stop normally. For example, the run method has been executed.

2: abnormal stop, may be interrupted by other threads, etc.

OK. See the method in JDK as an example.

We can see the interrupt and Ti? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcLe9t6i2vL/J0tTNo9a5z9 + v8 + v8/CzqrKssO0sru9qNLpyrnTw8TYo7 +/Rewrite" brush: java; "> @ Deprecated public final synchronized void stop (Throwable obj) {if (obj = null )......

We can see that the first stop is a synchronized method. When we talk about the synchronized keyword, we can't call the synchronized Method in a class, because the locks required by the two are the same, if we set the run method to synchronized, there is no way to stop the thread by calling stop. So what should we do?

For more information, see refer to examples. Replace stop with volatile and interrupt.

Public class ThreadStopTest1 {public static void main (String [] args) throws Exception {MyThread1 t1 = new MyThread1 (); t1.startThread (); Thread. sleep (3000); t1.stopThread () ;}} class MyThread1 extends Thread {private volatile boolean isRunning; public synchronized void startThread () {isRunning = true; this. start () ;}@ Overridepublic void run () {while (isRunning) {// doSomethingSystem. out. println ("I am working"); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println ("STOPPED");} public synchronized void stopThread () {isRunning = false ;}}
However, the above program is faulty, because the essence is to judge the isRunning value. If the code in the round-robin process is wait or sleep, it may keep waiting, the thread cannot be stopped. OK, we add interrupt. Let's talk about this keyword in the next article. The modification code is as follows:

Public class ThreadStopTest2 {public static void main (String [] args) throws Exception {MyThread2 t1 = new MyThread2 (); t1.startThread (); Thread. sleep (1000); t1.stopThread () ;}} class MyThread2 extends Thread {private volatile boolean isRunning; public synchronized void startThread () {isRunning = true; this. start () ;}@ Overridepublic void run () {long currentTime = System. currentTimeMillis (); while (isRunning) {System. out. println ("I am working"); try {Thread. sleep (10000);} catch (InterruptedException e) {System. out. println ("running" + (System. currentTimeMillis ()-currentTime)/1000 + "seconds") ;}} System. out. println ("STOPPED");} public synchronized void stopThread () {isRunning = false; this. interrupt ();}}
In this way, even when the code is sleep or wait, we forcibly call interrupt to throw an exception to the thread to achieve the goal. But in fact it still has a problem, that is, if the Code is not in wait or sleep, for example, the accept of serversocket, it will block the wait, then interrupt cannot interrupt the thread, look at the Code:

Public class ThreadStopTest2 {public static void main (String [] args) throws Exception {MyThread2 t1 = new MyThread2 (); t1.startThread (); Thread. sleep (1000); t1.stopThread () ;}} class MyThread2 extends Thread {private volatile boolean isRunning; public synchronized void startThread () {isRunning = true; this. start () ;}@ Overridepublic void run () {long currentTime = System. currentTimeMillis (); while (isRunning) {System. out. println ("I am working"); try {ServerSocket SC = new ServerSocket (80); System. out. println ("will be waiting ...... "); SC. accept ();} catch (Exception e) {System. out. println ("running" + (System. currentTimeMillis ()-currentTime)/1000 + "seconds") ;}} System. out. println ("STOPPED");} public synchronized void stopThread () {isRunning = false; this. interrupt ();}}

Therefore, you must pay attention to these issues in the actual code.

Another method recommended in the official article is similar in principle. It uses wait and policy to simulate thread suspension and restoration. I will not post code here. If necessary, refer to that article.

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.