public void Thread.interrupt(); //中断线程,设置中断标志位 public void Thread.isInterrupted(); //判断是否被中断 public void Thread.interrupted(); //判断是否被中断,并清除当前中断状态
最近在研究多线程,开始并不是太清楚三者的区别,尤其后两者,仔细想了个小例子,例子如下
线程类:
public class MyThread extends Thread{
@Override
public void run() {
boolean flag=false;
boolean interrupted;
//死循环等待线程中断
while(true){
if(flag==false){
//当前线程状态如果为中断,赋给变量flag
interrupted = Thread.interrupted();
if(interrupted==true){
System.out.println("MyThread 线程状态为"+interrupted);
}
flag=interrupted;
}
//如果线程中断,这里打印且复位中断标志位
if(flag){
System.out.println("MyThread 已经被中断");
interrupted=Thread.interrupted();
System.out.println("复原 MyThread中断状态位");
flag=interrupted;
}
}
}
}
Run类:
public class Run {
@SuppressWarnings("static-access")
public static void main(String[] args) {
MyThread my=new MyThread();
my.start();//开启子线程
my.interrupt();//中断子线程
try {
Thread.sleep(2000);//主线程sleep 2秒,让子线程充分运行
} catch (InterruptedException e) {
e.printStackTrace();
}
//死循环,如果子线程中断状态为非中断,则中断子线程,然后打印
while(true){
if(!my.isInterrupted()){
my.interrupt();
System.out.println("main 线程查看MyThread线程状态为"+my.isInterrupted()+"------------------");
}
}
}
}
这个例子很简单,主线程先去中断子线程,子线程检测到中断后再恢复,然后主线程一直去中断,子线程一直恢复。
这里了解了:
1:中断线程只是一个标识位,并非真正的中断线程不让其执行,如果真要让其中断不在运行自己去实现(异常法,sleep,wait,join,线程正在阻塞中调用中断,会使线程抛出异常从而使线程结束)。
2:中断标识位是可以被恢复的,并且可以多次进行。
3:interrupted()再次调用会恢复中断标识位为false(true表示线程中断).
4:对三者的作用与用法有个具体了解。