本文共 2095 字,大约阅读时间需要 6 分钟。
java很多停止线程的方法不被推荐,下面介绍用interrupt停止线程,
interrupt停止线程的原理就是打一个标记(初始为false),在run方法中运行时一直去判断这个标记,如果标记变为true,我们就选择不再执行,这样就达到了,停止的效果,
但是这样仅仅是结束了本次循环,并没有停止线程往下执行,如果,想直接跳出,可以用异常实现。
先介绍停止循环:
public class MyThread extends Thread{ @Override public void run() { super.run(); for(int i=0;i<500000;i++){ if(this.isInterrupted()){ System.out.println(i); System.out.println("已经是停止状态了!我要退出了!"); break; } } System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!"); }}
public class Run { public static void main(String[] args){ try { MyThread thread=new MyThread(); thread.start(); Thread.sleep(2); thread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); }}37617 end! 已经是停止状态了!我要退出了! 我被输出,如果此代码是for又继续运行,线程并未停止!
可以看到,线程跳出了循环,但是并没有结束。
通过异常实现结束:
public class MyThread extends Thread{ @Override public void run() { super.run(); try { for(int i=0;i<500000;i++){ if(this.isInterrupted()){ System.out.println(i); System.out.println("已经是停止状态了!我要退出了!"); throw new InterruptedException(); } } System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!"); } catch (InterruptedException e) { System.out.println("进MyThread.java类run方法中的catch了!"); e.printStackTrace(); } }}
public class Run { public static void main(String[] args){ try { MyThread thread=new MyThread(); thread.start(); Thread.sleep(2); thread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); }}20641 java.lang.InterruptedException end! 已经是停止状态了!我要退出了! at com.mr.two.MyThread.run(MyThread.java:15) 进MyThread.java类run方法中的catch了!
转载地址:http://vojqi.baihongyu.com/