现有线程对象threadA,调用threadA.interrupt(),则threadA中interrupted状态会被置成false,很多线程中都是通过isInterrupted()方法来检测线程是否中断,但在使用该过程中需要注意,run()方法中是否有其他代码捕获了InterruptedException异常,如果是,则会出现线程无法中断的可能性,主要代码如下:

public class DemoTest() {
public static void main(String[] args) {
new DemoTest();
} public DemoTest() {
ThreadTest threadTest = new ThreadTest();
threadTest.start();
Thread.sleep(1000);
threadTest.interrupt();//此处想中断线程,如果在中断的时刻,刚好该线程处于sleep状态,则会被该线程的sleep方法的异常捕获
} class ThreadTest extends Thread {
public void run() {
while(!isInterrupted()) { /**
* your business code
* blah.blah......
*/
try {
Thread.sleep(1000);//you may need take a break
} catch(InterruptedException e) {
Thread.currentThread.interrupt();//此处关键,调用当前线程interrupt()方法,可能会导致想中断的线程无法中断,需再次调用当前线程的interrupt()方法
}
}
}
} }
04-14 10:27