thread interrupt

Thread thread4 = new Thread(){
public void run(){
try {
//synchronized(this){
//this.wait(10000);
System.out.println("start A4");
System.out.println("A4 interrupt "+currentThread().isInterrupted());
currentThread().sleep(100000);
long time= System.currentTimeMillis();
while(System.currentTimeMillis()-time<20000)
{

}
System.out.println("end A4");
//}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("B4");
System.out.println("B4 interrupt "+currentThread().isInterrupted());
}
}

};

thread4.start();
//主线程休眠 start
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("B5");
}
主线程休眠 end
System.out.println("interrupt...start");
thread4.interrupt();

System.out.println("interrupt...end");



如上代码,interrupt的作用就是设置打断状态true或者false;
如果调用过thread4.interrupt(); 则再调用sleep join wait就会抛出InterruptedException异常,并且再次把interrupt状态设置为false;如果没有调用sleep join wait,那么我们可以发现在thread4.interrupt()之后currentThread().isInterrupted()为true。


第二种情况 当被block之后,我发现也会抛出InterruptedException,代码如下
Thread thread4 = new Thread(){
public void run(){
try {
//synchronized(this){
//this.wait(10000);
System.out.println("start A4");
System.out.println("A4 interrupt "+currentThread().isInterrupted());
BlockingQueue<String> q= new ArrayBlockingQueue<String>(2);
q.put("d");
q.put("d");
q.put("d");
System.out.println("end A4");
//}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("B4");
System.out.println("B4 interrupt "+currentThread().isInterrupted());
}
}

};

thread4.start();
// try {
// Thread.sleep(5000l);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// System.out.println("B5");
// }
System.out.println("interrupt...start");
thread4.interrupt();

System.out.println("interrupt...end");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值