Interrupt

145 阅读1分钟
public void interrupt()

interrupt用于中断本线程;

如果当前线程没有中断它自己,则该线程的 checkAccess 方法就会被调用,这可能抛出SecurityException;         如果线程在调用 Object 类的 wait()wait(long)wait(long, int) 方法,或者该类的 join()join(long)join(long, int)sleep(long)sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。{interrupt()会立即将线程的中断标记设为true,但是由于线程处于阻塞状态,所以该“中断标记”会立即被清除为false,同时产生一个InterruptedException的异常}
如果以前的条件都没有保存,则该线程的中断状态将被设置。
中断一个不处于活动状态的线程不需要任何作用。


中断处于blocked状态的线程
@Override
public void run() {
    try {
        while (true) {
            
        }
    } catch (InterruptedException e) {  
        // 由于exception而退出while循环,线程终止
    }
}
中断处于running状态的线程
@Override
public void run() {
    while (!isInterrupted()) {      }
  }


public class ThreadTest {
    static byte[] obj = new byte[0];
    public static void main(String[] args) throws InterruptedException {
        ThreadA a = new ThreadA("a");
        a.start();
        Thread.sleep(1000);
        a.interrupt();
        System.out.println("interrupt--->" + a.getState());
        Thread.sleep(1000);
        System.out.println("end--->" + a.getState());
    }
}
class ThreadA extends Thread {
    int i = 0;
    public ThreadA(String name) {
        super(name);    
    } 
   @Override
   public void run(){
        try{
            while (!isInterrupted()){
                Thread.sleep(200);
                System.out.println(getState() + " --->" + i++);
            }
        } catch (InterruptedException e) {
            System.out.println("exception break --->" + getState());
        }
    }
}