您的位置:首页 > 其它

Thread中的interrupt(),interrupted(),isInterrupted()方法的详解

2016-12-18 20:44 609 查看
1.interrupt()

  使用来中断线程作用的。除非当前线程处于中断状态,这个方法总是可以被执行的。如果当前线程被
Object#wait() wait(long)
或者
Thread#join() join(long),sleep()
方法所阻塞时,然而中断状态将被清空变成
false
,如果被IO/NIO阻塞,使用该方法,中断状态将被设置成
true
,未中断状态为
false
,中断状态为
true


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


3.isInterrupted()

返回线程中断状态,调用isInterrupted()方法不会影响中断状态。

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


结果

main interrupt before false
main interrupt after once true
main interrupt after twice true
main interrupt after three true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程