大多数停止一个线程的操作使用Thread.interrupt()方法,尽管方法的名字是“停止,终止”的意思,但这个方法不会终止一个正在运行的线程,还需要加入一个判断才可以完成线程的终止
在java中有以下3中方法可以终止正在运行的线程:
1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
2)使用stop方法强行终止线程,但是不推荐使用这个方法,因为stop和suspend及resume一样,都是作废过期的方法,使用它们可能产生预料不到的结果
3)使用interrupt方法中断线程
3.1 抛出异常,中断线程。通常抛出异常是和interrupt配合使用,不建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,时线程终止的时间的得以传播
3.2 使用return停止线程
将方法interrupt()与return结合使用也能实现停止线程的效果
重点说一说使用interrupt方法进行中断
一、异常抛出中断线程
package com.slowly.interruptThread;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for(int i=0;i<500000;i++){
if(this.interrupted()){
System.out.println("已经是停止状态了!我要退出了!");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.slowly.interruptThread;
public class Run {
public static void main(String[] args){
try{
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("end!");
}
}
运行结果
二、利用sleep()和interrupt()来抛出异常中断线程
上面的Run类不变,MyThread修改成如下:
package com.slowly.interruptThread;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中国停止!");
e.printStackTrace();
}
}
}
运行结果
三、使用return停止线程
同样,修改MyThread线程如下
package com.slowly.interruptThread;
public class MyThread extends Thread {
@Override
public void run() {
while(true){
if(this.isInterrupted()){
System.out.println("停止了!");
return;
}
System.out.println("timer="+System.currentTimeMillis());
}
}
}
运行结果
《Java多线程编程核心技术》