调用interrupt()方法仅仅是在线程中打了一个停止的标记,并不是真的停止线程。(想中断哪个线程,就给哪个线程打标)
public class Run {
public static void main(String[] args) {
CountOperate c=new CountOperate();
Thread thread=new Thread(c);
c.setName("ATest");
try{
Thread.sleep(2000);
c.start();
//给 main线程 打一个中断的标记
Thread.currentThread().interrupt();
//给 CountOperate线程 打一个中断的标记
c.interrupt();
//给 thread线程 打一个中断的标记
thread.interrupt();
}catch (InterruptedException e){
}
}
}
但是并不会停止线程,需要增加一个判断线程的状态。
Thread.java中提供了两种方法:
1、interrupted()方法
//静态方法,哪一个线程调用该方法,那么就判断该线程是否终止
//与具体的线程对象无关,只与方法存在的位置有关
//能够清除状态
public static boolean interrupted();
例如:
public class Run {
public static void main(String[] args) {
CountOperate c=new CountOperate();
Thread thread=new Thread(c);
c.setName("ATest");
try{
Thread.sleep(2000);
//给 main线程 打一个中断的标记
Thread.currentThread().interrupt();
//给 thread线程 打一个中断的标记
//仅仅是中断thread线程,而不会中断 c 线程
thread.interrupt();
//需要单独中断 c 线程
c.interrupt();
System.out.println("main线程是否中断:"+Thread.interrupted());
System.out.println("main线程是否中断:"+Thread.interrupted());
System.out.println("thread线程是否中断:"+thread.interrupted());
}catch (InterruptedException e){
}
}
}
//运行结果:
//Thread.interrupted()方法是在main线程中运行的,所以true
main线程是否中断:true
//interrupted()方法具有清除状态的功能,连续两次调用该方法,则第二次就会返回false
main线程是否中断:false
//不是在thread线程 中运行interrupted()方法,所以判断为false
thread线程是否中断:false
2、isInterrupted()方法
//与具体的对象有关
//不能清除状态
public boolean isInterrupted()
例子:
public class Run {
public static void main(String[] args) {
CountOperate c=new CountOperate();
Thread thread=new Thread(c);
c.setName("ATest");
try{
Thread.sleep(2000);
thread.start();
//给 main线程 打一个中断的标记
Thread.currentThread().interrupt();
//给 thread线程 打一个中断的标记
//仅仅是中断thread线程,而不会中断 c 线程
thread.interrupt();
System.out.println("main线程是否中断:"+Thread.currentThread().isInterrupted());
System.out.println("main线程是否中断:"+Thread.currentThread().isInterrupted());
System.out.println("thread线程是否中断:"+thread.isInterrupted());
}catch (InterruptedException e){
}
}
}
//结果
//与指定的线程对象有关,并不会清除状态,所以连续调用还是返回true
main线程是否中断:true
main线程是否中断:true
//与具体的线程对象有关的
thread线程是否中断:true
二、停止线程
2.1、异常方法
现在可以根据线程的状态来中断线程。
public class CountOperate extends Thread {
private String name;
public void run(){
try{
for(int i=0;i<5000;i++){
//判断线程是否中断
//中断之后,抛出异常,中断线程的执行
//也可以使用this.isInterrupted()
if(this.interrupted()){
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
2.2、sleep()状态下停止线程
2.3、使用stop()停止线程(不建议)
调用stop()方法时会抛出ThreadDeath异常,该方法已经被作废,如果强制让线程停止则有可能使一些清理性的工作得不到完成。另一个情况就是对锁定的对象进行解锁,导致数据得不到同步的处理,出现数据不一致的问题。
2.4、使用return停止线程
public class CountOperate extends Thread {
private String name;
public void run(){
while(true){
if(this.isInterrupted()){
return;
}
}
}
}