思路为:
在调用thread.start()
方法之后,调用thread.interrupt()
方法来中断这个线程。在thread的run()
方法中,运行之前要检查本线程是否被中断(用this.interrupted()
或this.isInterrupted()
,前者为静态方法,感觉没什么区别),如果被中断,则要throw一个InterruptedException
,从而导致run()方法停止运行,转到catch语句。
示例代码 如下:
MyThread类
public class MyThread extends Thread {
@Override
public void run(){
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (this.isInterrupted()) { //检测是否被中断
System.out.println("I has been interrupted, I will go away");
throw new InterruptedException(); //抛异常
}
System.out.println("i: " + i);
}
System.out.print("this is sentence after for loop");
}
catch(InterruptedException ie){//捕获异常
System.out.print("this is catch clause");
}
}
}
运行测试类Run:
public class Run {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.interrupt();//中断这个线程
System.out.print("end");
}
}
关于this.interrupted()
和this.inInterrupted()
检测方法的说明,
前者为测试当前线程是否已经是中断状态,执行后具有将状态标志清除为false的功能,连续调用时,第二次检测结果为false;
后者测试线程Thread对象是否已经是中断状态,不清楚标志。
另外,如何停止一个正在休眠(正在sleep()
方法中)的线程?,调用sleep方法时,必须显式捕获InterruptException。sleep()方法在检测到异常时会自动抛出中断异常,
thread.interrupt()会使isInterruped()标志为true,从而可以捕获异常。
thread.stop()会抛出Java.lang.ThreadDeath异常,stop方法已经过期,不应该被使用
参考《Java多线程编程核心技术》