interrupt()和interrupted

  • 1.interrupt() 

interrupt()的作用是中断本线程。
本线程中断自己是被允许的;其它线程调用本线程的interrupt()方法时,会通过checkAccess()检查权限。这有可能抛出SecurityException异常。
如果本线程是处于阻塞状态:调用线程的wait(), wait(long)或wait(long, int)会让它进入等待(阻塞)状态,或者调用线程的join(), join(long), join(long, int), sleep(long), sleep(long, int)也会让它进入阻塞状态。

若线程在阻塞状态时,调用了它的interrupt()方法,那么它的“中断状态”会被清除并且会收到一个InterruptedException异常。例如,线程通过wait()进入阻塞状态,此时通过interrupt()中断该线程;调用interrupt()会立即将线程的中断标记设为“true”,但是由于线程处于阻塞状态,所以该“中断标记”会立即被清除为“false”,同时,会产生一个InterruptedException的异常。
如果线程被阻塞在一个Selector选择器中,那么通过interrupt()中断它时;线程的中断标记会被设置为true,并且它会立即从选择操作中返回。
如果不属于前面所说的情况,那么通过interrupt()中断线程时,它的中断标记会被设置为“true”。
中断一个“已终止的线程”不会产生任何操作。

这里只举例sleep 上述其他方法也是同样效果:

public class InterruptTest
{
    public static void main(String[] args)
    {
        System.out.println(Thread.currentThread().getName()+" interrupt before "+Thread.currentThread().isInterrupted());
        Thread.currentThread().interrupt();
        System.out.println(Thread.currentThread().getName()+" interrupt after "+Thread.currentThread().isInterrupted());
    }
}

结果: 

main interrupt before false
main interrupt after true
class TestThread extends Thread
{
    public TestThread(String name){
        setName(name);
    }
    public void run()
    {
        try{
            Thread.sleep(10);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
public class InterruptTest
{
    public static void main(String[] args) throws InterruptedException
    {
        TestThread tt = new TestThread("test");
        tt.start();
        System.out.println(tt.getName()+" interrupt before "+tt.isInterrupted());
        tt.interrupt();//中断sleep将会清空中断状态
        Thread.sleep(1000);//等待test线程
        System.out.println(tt.getName()+" interrupt after "+tt.isInterrupted());

    }
}

结果:

test interrupt before false
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at thread2.TestThread.run(InterruptTest.java:11)
test interrupt after false
  • 2.interrupted 
      测试当前线程是否中断,这个方法将会清除中断状态,换句话说,如果这个方法被成功调用2次,第二次将会返回false,除非当前线程再次被中断,可以在第一个调用后,第二次调用前去检测它。
public class InterruptTest
{
    public static void main(String[] args) throws InterruptedException
    {
        System.out.println(Thread.currentThread().getName()+" interrupt before "+Thread.currentThread().interrupted());
        Thread.currentThread().interrupt();
        System.out.println(Thread.currentThread().getName()+" interrupt after once "+Thread.currentThread().interrupted());//调用之后清除中断状态
        System.out.println(Thread.currentThread().getName()+" interrupt after twice "+Thread.currentThread().interrupted());
    }
}

 结果:

main interrupt before false
main interrupt after once true
main interrupt after twice false

猜你喜欢

转载自blog.csdn.net/luzhensmart/article/details/82941220
今日推荐