我们先了解一下:public boolean isinterrupted()
其作用就是检测某线程是否被中断
故通过一个睡眠线程和死循环线程做一个例子
public static void main(String[] args) {
//睡眠线程
Thread sleepThread = new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.run();
}
};
//死循环线程
Thread willThread = new Thread(){
@Override
public void run() {
while (true);
}
};
//启动两个线程
sleepThread.start();
willThread.start();
//中断
sleepThread.interrupt();
willThread.interrupt();
//判断该线程是否被中断
while (sleepThread.isInterrupted()){
System.out.println("线程睡眠中,不会被中断");
};
System.out.println("sleepThread: "+sleepThread.isInterrupted());
System.out.println("whileThread: "+willThread.isInterrupted());
}
其运行结果:
根据这个例子可知,interrupt只能等到线程醒来才能去中断