How to interrupt the "synchronization/blocking" thread, not only interrupt ()

Source: Internet
Author: User

How to interrupt a running thread?

Thread interruption means that the thread stops all ongoing operations before it completes the task, effectively suspending its current operation.

Then, the thread waits for a new task, or continues to run to the next step.

 

[Method 1] use the shared variable

1. The thread needs to periodically check this variable and then abort the task in an orderly manner.

2. Define a shared variable as a "volatile" type, or block all its methods into the "synchronized" block or method.

3. Limitations: If the thread is blocked, the shared variable cannot be verified and the method will become invalid. For example, object. Wait (), serversocket. Accept (), datagramsocket. Receive (), and so on.

 

public class Main extends Thread {

 

    volatile boolean stop = false;

 

    public static void main(String[] args) {

 

        Main thread = new Main();

 

        try {

            System.out.println("starting thread");

            thread.start();

            Thread.sleep(3000);

            System.out.println("asking thread to stop");

            thread.stop = true;

            Thread.sleep(3000);

            System.out.println("stopping application");

        } catch (InterruptedException e) {

            System.out.println("sleep interrupted");

            ;

        }

    }

 

    public void run() {

While (! Stop) {// periodic check

            System.out.println("running");

            long time = System.currentTimeMillis();

            while (System.currentTimeMillis() - time < 1000) {

                ;

            }

        }

        System.out.println("thread exiting under request..");

    }

}

 

 

Method 2: For blocking, Use thread. Interrupt ()

(1) interrupt (), will not interrupt a running thread, it actually completes, In the thread"BlockedThrows an interruption signal so that the thread can exit the blocking state. To be more specific, if the thread is. wait (), thread. join () and thread. if sleep () is blocked by one of the three methods, it will receive an interrupt exception (interruptedexception) to terminate the blocked state early.

(2) Limitations: interrupt () can effectively rescue the blocked threads, but it will still be unable to be interrupted if the CPU is used for a long time.

public class Main extends Thread {

    boolean stop = false;

    public static void main(String[] args) {

        Main thread = new Main();

        try {

            System.out.println("starting thread");

            thread.start();

            Thread.sleep(3000);

            System.out.println("asking thread to stop");

Thread. Stop = true; // If the thread is blocked, this variable is not checked.

Thread. Interrupt (); // interrupt

            Thread.sleep(3000);

            System.out.println("stopping application");

        } catch (InterruptedException e) {

            System.out.println("sleep interrupted");

            ;

        }

    }

 

    public void run() {

        while (!stop) {

            System.out.println("running");

            try{

                Thread.sleep(1000);

            }catch(InterruptedException e){

                System.out.println("Thread interrupted");

            }

        }

        System.out.println("thread exiting under request..");

    }

}

 

[Method 3] "brutal" behavior

(1) For synchronization, you can enable a "disturbing" thread to throw a runtimeexception.

For example, if synchronization is waiting to be done in main thread:

A) thread B is enabled in thread A. What we do: Sleep (timeout) time. When we wake up, A runtimeexception is thrown;

B) do some things in a, and sync with Shenma;

C) the timeout time is reached. If 2) is not over yet, runtimeexception will also end it;

(2) Disadvantage: This method throws a runtimeexception and cannot catch the exception. Naturally, it means that it cannot be processed.

 

Semaphore s = new Semaphore(0);

Timeoutthread T = new timeoutthread (5000l, new timeoutexception ("timeout "));

try {

    t.start();

    

// Synchronous waiting code

    System.out.println("try to acquire");

    s.acquire();

    System.out.println("acquired");

    

    t.cancel();

}catch (InterruptedException e) {

    System.out.println("interrupt exception");

}

 

[Method 4 ]......

 

 

 

[Note ]:

(1) Not recommended: thread. Stop ()

(2) using interrupt in this way does not actually interrupt the thread, so do not be blinded by the name:

public class Main extends Thread {

 

    volatile boolean stop = false;

 

    public static void main(String[] args) {

 

        Main thread = new Main();

 

        try {

            System.out.println("starting thread");

            thread.start();

            Thread.sleep(3000);

            System.out.println("Interrupting thread");

Thread. Interrupt (); // The thread is not actually interrupted, but the interrupt bit is set.

            Thread.sleep(3000);

            System.out.println("stopping application");

        } catch (InterruptedException e) {

            System.out.println("sleep interrupted");

            ;

        }

 

    }

 

    public void run() {

        while (!stop) {

            System.out.println("running");

Long time = system. currenttimemillis (); // this operation has been occupying the CPU and is not "congested". Therefore, interrupt () is useless and does not take effect.

            while (System.currentTimeMillis() - time < 1000) {

                ;

            }

        }

        System.out.println("thread exiting under request..");

    }

 

}

 

 

 

 

Http://wenku.baidu.com/view/1586ccea81c758f5f61f6751.html

Http://java.chinaitlab.com/base/786639.html

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.