引入
停止线程是在多线程开发时很重要的技术点,掌握此技术可以对线程的停止进行有效的处理。停止一个线程意味着在线程处理完任务之前停掉正在做的操作,也就是放弃当前操作。
判断线程是否是停止状态
Thread类中提供了两种方法,interrupted()和isInterrupted(),下面做详细介绍。
interrupted( )方法
方法声明:public static boolean interrupted()
含义:测试当前线程是否已经中断。线程中断状态由该方法清除。换句话说,如果连续两次调用此方法,则第二次调用将返回false。isInterrupted( )方法
方法声明:public boolean interrupted()
含义:测试线程是否已经中断。不清楚状态标识。
中断线程的方法
当线程的run方法执行方法体中最后一条语句后,并经由垂直型return语句返回时,或者出现了在方法中没有捕获的异常时,线程将终止。在java的早期版本中还有一个stop方法,后被弃用。iterrupt方法可以用来请求终止线程,当对一个线程调用interrupt方法时,线程的中断状态将被置位。这是每一个线程都具有的boolean标志。每个线程都应该不时的检查这个标志,以判断线程是否被中断。但是,如果线程被阻塞(sleep或wait),就无法检测中断状态。这是会产生InterruptedException异常的地方。
package page.thread.two;
public class MyThread extends Thread{
public void run(){
super.run();
try {
for(int i=0;i<500000;i++){
if(this.isInterrupted()){
System.out.println("已经是停止状态了,要退出");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
System.out.println("在for之下");
} catch (InterruptedException e) {
System.out.println("进入MyThread类run方法中的catch");
e.printStackTrace();
}
}
}
package page.thread.two;
public class Run {
public static void main(String[] args) throws InterruptedException {
try{
MyThread mt=new MyThread();
mt.start();
Thread.sleep(2000);
mt.interrupt();
}catch(InterruptedException e){
System.out.println("main catch");
e.printStackTrace();
}
}
}
运行结果: