您的位置:首页 > 编程语言 > Java开发

java Thread interrupt方法

2017-06-30 11:42 411 查看
1、interrupt用于打断【正在执行】的线程:interrupt方法有两个作用,一个是将线程的中断状态置位(中断状态由false变成true);另一个则是:让被中断的线程抛出InterruptedException异常

(1)如果当前运行线程处于sleep或wait状态,interrupt会打断此状态,并抛出InterruptedException异常

(2)如果当前运行线程没有处于sleep或wait状态,该方法只是将线程的interruptedStatus=true,

此时可以通过两种方式获取线程中断状态:

Thread类静态方法:Thread.interrupted(),如果该线程被打断,方法返回true,同时将interruptStatus还原(即设置为false),因此连续调用两次,第二次返回false

测试代码

public class TestInterruptThread {

public static void main(String[] args) {
InterruptThread interruptThread = new InterruptThread();
interruptThread.start();

interruptThread.interrupt();
System.out.println("done");
}
}

class InterruptThread extends Thread {
@Override
public void run(){
for(int i=0;i<3;i++){
if(Thread.interrupted()){
System.out.println("front....");
} else {
System.out.println("end.....");
}
}

System.out.println("thread continue working.....");
}
}


测试结果
done
front....
end.....
end.....
thread continue working.....


Thread类实例方法:this.isInterrupted(),如果该线程被打断,该方法始终返回true
测试代码


public class TestInterruptThread {

public static void main(String[] args) {
InterruptThread interruptThread = new InterruptThread();
interruptThread.start();

interruptThread.interrupt();
System.out.println("done");
}
}

class InterruptThread extends Thread {
@Override
public void run(){
for(int i=0;i<3;i++){
if(this.isInterrupted()){
System.out.println("front....");
} else {
System.out.println("end.....");
}
}

System.out.println("thread continue working.....");
}
}


测试结果


done
front....
front....
front....
thread continue working.....


实际上,检测到线程被中断后应该立即停止任务执行

class InterruptThread extends Thread {
@Override
public void run(){
for(int i=0;i<3;i++){
if(this.isInterrupted()){
break;   // 检测到线程被中断应该停止执行业务逻辑
} else {
System.out.println("end.....");
}
}
System.out.println("thread continue working.....");   // 仍然会执行
}
}


线程被中断后,并没有立即停止运行,如果想要立即停止,可以抛出异常

class InterruptThread extends Thread {
@Override
public void run(){
for(int i=0;i<3;i++){
if(this.isInterrupted()){
throw new RuntimeException("中断后停止当前线程");
} else {
System.out.println("end.....");
}
}
System.out.println("thread continue working.....");   // 不会执行了
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: