优雅的停止线程在多线程中很关键
- 指当前线程结束本任务的操作后,停止并收回线程,而不是暴力的直接停止线程。
- Thread.stop() 函数,废弃,不优雅不安全
- return; 与 break;,不建议,会有代码污染(不要在 try 里面写 return)
- 异常的方式停止多线程,推荐,不会弄脏代码,还有日志
- interrupt() 方法用于中断线程
- interrupted() 是静态方法,返回的当前线程的中断状态。如果当前线程被中断且没有抛出中断异常那么中断状态不会被清除,否则中断状态就会被清除
- isInterrupted() 仅仅查询中断标志位来判断是否发生中断
- interrupt()的缺点:interrupted() 只能停止主线程,而无法停止多线程,因为 interrupted() 首先需要标记一个停止线程的位置,然后才会停止线程
- interrupt(),如果此线程在调用该类的 Object class 或 join() 、 join(long) 、 sleep(long,int) 方法、wait() 、 wait(long) 或 wait(long,int) 方法时被阻止,则其中断状态将被清除,并将收到 InterruptedException
- 所以用异常的方式停止线程
- interrupt() + 手动 new 异常
- interrupt() + sleep()
- interrupt() + wait() 不要让他们相遇
class MyThread extends Thread{
@Override
public void run(){
try{
while(true){
if(this.interrupted()){
System.out.println("isInterrupted:" + this.isInterrupted());
throw new InterruptedException();
}
System.out.println("不会输出");
}
} catch(InterruptedException exception){
System.out.println("进入异常");
}
}
}
public class test0{
public static void main(String[] args){
Thread myThread = new MyThread();
myThread.start();
myThread.interrupt();
}
}
class MyThread extends Thread{
@Override
public void run(){
try{
while(true){
Thread.sleep(1000);
System.out.println("不会输出");
}
} catch(InterruptedException exception){
System.out.println("进入异常");
}
}
}
public class test1{
public static void main(String[] args){
Thread myThread = new MyThread();
myThread.start();
myThread.interrupt();
}
}