Java Thread Interruptedexception__java

Source: Internet
Author: User
Tags instance method thread class volatile
1. Interruptedexception Exception Overview

When a method declares that a interruptedexception exception might be thrown, it is a method that may take a little time, but can be canceled.

The interruptedexception of the parabolic method are:

1. Java.lang.Object type of Wait method

2. Sleep method of Java.lang.Thread class

3. Join method of Java.lang.Thread class

--a way to spend some time

The thread that executes the wait method enters the waiting area waiting to be notify/notify all. During the wait, the thread will not be active.

The thread that executes the sleep method pauses the time set in the execution parameter.

The thread that executes the join method waits until the specified thread ends.

Therefore, the above method is a way to take a little time.

--a method that can be canceled

Because an operation that takes time reduces the responsiveness of the program, it may be canceled/abandoned to execute this method.

This is mainly done by interrupt method.

1. Sleep method and Interrupt method

The interrupt method is an instance method of the thread class, which does not need to get a lock on the thread instance at any point in time, and any thread can invoke the interrupt method of another thread at any moment through the thread instance.

When a thread in sleep is called interrupt method, the paused state is discarded and the interruptedexception exception is thrown, so that the control of the thread is given to the catch block that catches the exception.

2. Wait method and interrupt method

When a thread calls the wait method, the thread locks in when it enters the waiting area. When you call the interrupt method on a thread in wait, the lock is retrieved first, then the interruptedexception exception is thrown, and the interruptedexception exception cannot be thrown until the lock is fetched.

3. Join method and Interrupt method

You can use the interrupt method to cancel a thread as it waits for the other thread to end with the Join method. Because the join method does not need to acquire a lock, as with sleep, it jumps immediately to the catch program block

--What did the interrupt method do.

The interrupt method actually only changes the state of interruption.

The internal methods of sleep, wait, and join are constantly checking the value of the interrupt state to throw interruptedexception.

So, if the thread does other processing, and the interrupt method is invoked, the thread will not throw the interruptedexception, only when it comes to sleep, wait, join these methods, Will throw interruptedexception. If there is no call to sleep, wait, join these methods, or no online Chengri themselves to check the interrupt state, you throw interruptedexception, that interruptedexception will not be thrown out.

Isinterrupted method, which can be used to check the interrupt status

The Thread.Interrupt method, which can be used to check for and clear the interrupt state, interrupt the method can only break a thread that is blocking and not function in a running thread.



2. How to break a thread:

1. Use shared variable to send a signal telling the thread that the running task must be stopped. The thread must periodically check this variable (especially during a redundant operation) and then abort the task in an orderly manner.

Package threadlocaltest;

public class TestCase extends Thread {

	volatile Boolean stop = false;

	public static void Main (string[] args) throws interruptedexception {
		TestCase thread = new TestCase ();

		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 ...");

	}

	public void Run () {while
		(!stop) {

			System.out.println (' Thread is running ... ');

			Long time = System.currenttimemillis ();

			while (the System.currenttimemillis ()-time < 1000) && (!stop)) {

			}

		}
		System.out.println (" Thread exiting under request ... ");

	}



Starting thread ...
Thread is running ...
Thread is running ...
Thread is running ...
Thread is running ...
Asking thread to stop
... Thread exiting under request ...
Stopping application ...

2. For methods that are likely to be blocked, the correct stopping thread is to set the shared variable and invoke interrupt (note that the variable should be set first). If the thread is not blocked, then the call to interrupt () will not work, otherwise the thread will get an exception (the thread must be prepared to handle this condition), and then flee the blocking state. In either case, the last thread checks the shared variable and then stops. Listing C This example describes the technique.

Package threadlocaltest;

public class Threadbasic extends Thread {

	volatile static Boolean stop = FALSE;
	public static void Main (string[] args) throws interruptedexception {

		Threadbasic thread = new Threadbasic ();
		SYSTEM.OUT.PRINTLN ("Starting thread ...");
		Thread.Start ();
		Thread.Sleep (1000);
		SYSTEM.OUT.PRINTLN ("Asking Thread to stop ...");
		Stop=true;
		Thread.Interrupt ();
		Thread.Sleep (3000);
		SYSTEM.OUT.PRINTLN ("Stopping application ...");
	}

	public void Run () {while

		(!stop) {
			System.out.println ("Thread running ...");
			try {
				Thread.Sleep (3000);
			} catch (Interruptedexception e) {
				System.out.println ("Thread interrupted ...");
			}

			System.out.println ("Thread exiting under request ...");}


Starting thread ...
Thread Running
... Asking thread to stop
... Thread interrupted
... Thread exiting under request ...
Stopping application ...

3. How to deal with interruptedexception anomalies

1. Do not capture, pass it to the caller

2. Recover break status after capture

Sometimes throwing interruptedexception is not appropriate, for example, when a task defined by Runnable invokes an interruptible method. In this case, you can't throw interruptedexception again, but you don't want to do nothing. When a blocking method detects an interrupt and throws a interruptedexception, it clears the interrupt state. If you catch a interruptedexception but cannot throw it back, you should keep the evidence of the interruption so that the higher-level code in the call stack can know the interrupt and respond to the interrupt. The task can be done by calling interrupt () to "break" the current thread, as shown in Listing 3. At the very least, each time the interruptedexception is captured and not thrown back, the current thread is interrupted before it is returned.

public class Taskrunner implements Runnable {
    private blockingqueue<task> queue;

    Public Taskrunner (blockingqueue<task> queue) { 
        this.queue = queue; 
    }

    public void Run () { 
        try {
             while (true) {
                 Task task = Queue.take (timeunit.seconds);
                 Task.execute ();
             }
         catch (Interruptedexception e) { 
             //Restore the interrupted status
             Thread.CurrentThread (). interrupt ();
         }
    }
}




Interrupt Thread in

Handling Interruptedexception

Interruptedexception Introduction

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.