想停止线程?千万不要用stop()
在一定时候我们如果想停止线程怎么办?JDK中提供了stop方法,但是现在已经不建议使用了。
thread.stop();
这个方法会使线程突然停止,没有经过别的处理,所以在有的时候会造成脏读。在一些情况下,我们需要采取其他方式来停止线程。
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread1=new Thread(new TheThread(),"thread1");
thread1.start();
Thread.sleep(2000);
thread1.interrupt();
}
}
在有时候,我们需要使用中断,但是中断并没有停止进程,我们需要改进这方式。
我们采用异常来停止线程
public class Main {
public static void main(String[] args) throws InterruptedException {
try{
Thread thread1=new Thread(new TheThread(),"thread1");
thread1.start();
Thread.sleep(2000);
thread1.interrupt();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
class TheThread extends Thread{
public void run() {
super.run();
for (int i = 0; i < 10; i++) {
if(this.interrupted()){
break;
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
验证此方法是否可以停止线程。