Interrupts for Java threads (interruption)

Source: Internet
Author: User
Tags thread class volatile

It is easy to start tasks and threads. Most of the time, we will let them run until the end, or let them stop on their own. However, sometimes we want to end a task or thread prematurely, perhaps because the user canceled the operation, or the application needs to be shut down quickly. It is not easy for tasks and threads to stop An Shu, fast, and reliably. The Java thread class gives us a way to stop suspending threads, such as Stop (), suspend (), but the security issue is now deprecated. Java does not provide a secure preemptive method to stop a thread, but it provides interrupts (interruption), a collaborative mechanism that enables one thread to terminate the current work of another thread in a collaborative manner. This collaborative approach is necessary, and we rarely want a task, thread, or service to stop immediately, because this immediate stop causes the shared data structure to be in an inconsistent state. Instead, you can use a collaborative approach when writing tasks and services: When you need to stop, they first clear the work that is currently being performed, and then end. This provides greater flexibility because the task itself's code is clearer about how to perform the cleanup than the code that issued the cancellation request. The end-of-life (end-of-lifecycle) problem complicates the process of designing and implementing tasks, services, and programs, and this very important element in programming is often overlooked. One of the main differences between a well-behaved software and a barely-running software is that well-behaved software can handle the process of failure, shutdown, and cancellation in a perfect way.

How do you design a collaboration mechanism that allows threads to be safely interrupted? We can set a cancellation flag to check this flag where the worker thread will be interrupted, and when the interrupt flag is checked to be set to canceled, the worker thread begins to cancel the work.

1  Public classCancelablethreadImplementsRunnable {2 3     //thread cancellation flag, volatile modifier, guaranteed memory Visibility4     Private volatile BooleanisCanceled =false;5 6 @Override7      Public voidrun () {8          while(!iscanceled) {//polling this cancellation flag in the worker thread9System.out.println ("The current thread is doing something ...");TenSystem.out.println (Thread.CurrentThread (). GetName () + "Cancel flag is" +isCanceled); One         } A         //when the cancellation flag is set to True, execute the following code to do some cancellation work -System.out.println (Thread.CurrentThread (). GetName () + "The current Thread has been cancelled"); -     } the  -     Private voidCancel () { -isCanceled =true; -     } +}

1  Public classMain {2      Public Static voidMain (string[] args)throwsException {3 4Cancelablethread Cancelablethread =NewCancelablethread ();5         NewThread (Cancelablethread). Start ();6         Try {7Thread.Sleep (1);8}finally {9             //set flag bit to true, interrupt threadTen Cancelablethread.cancel (); One         } A     } -}

Printing results:

Thread-0 Cancel flag is falsethe current thread is doing something ... Thread-0 Cancel flag is falsethe current thread is doing something ... Thread-0 Cancel flag is falsethe current thread is doing something ... Thread-0 Cancel flag is falsethe current thread is doing something ... Thread-0 Cancel flag is truethread-0the current thread have been cancelled

 

In fact, the thread class provides us with three methods related to threading interrupts to implement these mechanisms. These three methods are:

 Public void interrupt () {  //...  Omit the relevant code  interrupt0 ();           // Just to set the interrupt flag          // ...  Omit related code }
 Public Static Boolean interrupted () {    return CurrentThread (). isinterrupted (true);
 Public Boolean isinterrupted () {    return isinterrupted (false);}
    1. The interrupt () method is primarily used to set the interrupt flag bit, if this thread is calling wait () for the object class, wait (long) or wait (Long,int) method or join (), join (long), join (Long,int), When the method of sleep (long) or sleep (Long,int) is blocked, its interrupt state is cleared and a Interruptedexception exception is received.
    2. The static interrupted () method is used to test if the front thread is interrupted, and calling this method clears the interrupt state of the threads. Call this method to return False if the thread has been interrupted;
    3. The isinterrupted () method is used to test if the thread is interrupted, but it does not clear the interrupt state.

View source discovery, static interrupted () and isinterrupted () methods are called private native Boolean isinterrupted (Boolean clearinterrupted); Depending on the value of the incoming clearinterrupted, determine whether to clear the interrupt flag bit.

1  Public classInterrupttest {2 3 4     Static classInnerthreadextendsthread{5 6 7 @Override8          Public voidrun () {9              while(!isinterrupted ()) {TenSystem.out.println (Thread.CurrentThread (). GetName () + "Cancle flag is" +isinterrupted ()); One                 Try { A  -Thread.Sleep (100); -  the}Catch(interruptedexception e) { - e.printstacktrace (); -                     //throw interruptedexception, interrupt flag bit is cleared, call interrupt again (); - interrupt (); +                 } -             } +System.out.println (Thread.CurrentThread (). GetName () + "Cancle flag is" +isinterrupted ()); A  at         } -     } -  -  -      Public Static voidMain (string[] args) { -Innerthread Innerthread =NewInnerthread (); in Innerthread.start (); -         Try { to  +Thread.Sleep (1000); -  the}Catch(interruptedexception e) { * e.printstacktrace (); $         }Panax Notoginseng innerthread.interrupt (); - //innerthread innerThread2 = new Innerthread (); the //Innerthread2.start (); + //innerthread2.interrupt (); A     } the}

Printing results:

THREAD-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseThread-0 cancle Flag isfalseJava.lang.InterruptedException:sleep interrupted at Java.lang.Thread.sleep (Native Method) at Interrupttest$inne Rthread.run (Interrupttest.java:13) Thread-0 cancle Flag istrue








Interrupts for Java threads (interruption)

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.