1.异常法(使用退出标志,使线程正常退出)
public class MyThread extends Thread{
public void run(){
super.run();
try {
for (int i = 0; i < 5000000; i++) {
if(this.interrupted()){
System.out.println("停止状态");
throw new InterruptedException();
}
System.out.println("i="+(i+1));
}
System.out.println("for 循环下面");
}catch (InterruptedException e){
System.out.println("进入catch");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt(); //这个地方相当于打上了中断标志,然后在异常中去处理
}catch (InterruptedException e){
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");
}
}
2.使用stop方法强行终止
该方法已经作废,因为会使数据产生不一致性,程序执行就不确定了
(suspend方法也同样已经被遗弃,因为该方法可能造成同步对象被一直占用,相当于死锁)
3.使用interrupt方法中断线程
使用interrupt()+return结合
public void run(){
while(true){
if(this.interrupted()){
System.out.println("停止了");
return;
}
System.out.println("timer=" + System.currentTimeMillis());
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.interrupt();
}
但是这个方法可能造成代码中出现多个return,造成污染
所以使用异常法来停止线程,在catch块中可以对异常信息进行相关处理,而且异常流能更好、更方便的控制程序的运行流程。不至于像第三种方法中可能出现多个return。