本文共 3177 字,大约阅读时间需要 10 分钟。
在Java中,当使用interrupt()方法停止一个线程时,仅仅在当前线程中打了一个停止的标记,并未真正停止线程。为了实现真正的线程停止,我们可以结合throw new InterruptedException()的方式来处理。
package com.kgf.test;public class MyThread extends Thread { @SuppressWarnings("static-access") @Override public void run() { try { for (int i = 0; i < 500000; i++) { if (this.interrupted()) { System.out.println("已经是停止状态了!我要退出了!"); throw new InterruptedException(); } System.out.println("i=" + (i + 1)); } System.out.println("我在for下面"); } catch (Exception e) { System.out.println("进入catch方法了。。。。。。"); e.printStackTrace(); } }} package com.kgf.test;public class Run { public static void main(String[] args) throws InterruptedException { try { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(1000); myThread.interrupt(); } catch (Exception e) { e.printStackTrace(); } System.out.println("==========END================"); }} 通过上述代码,我们可以看到,使用interrupt()方法在线程处于运行状态时会立即停止线程,并抛出InterruptedException异常。线程会进入catch块进行处理。
建议使用“抛异常”方式来实现线程的停止,因为在catch块中可以对异常信息进行相关的处理,而且使用异常流能更好、更方便地控制程序的运行流程。
当线程处于睡眠状态时,使用interrupt()方法停止线程会更加有效。
package com.kgf.test;public class MyThread extends Thread { @Override public void run() { try { System.out.println("===run begin====="); Thread.sleep(200000); System.out.println("===run end====="); } catch (Exception e) { System.out.println("在沉睡中被停止!进入catch!线程状态为:" + this.isInterrupted()); e.printStackTrace(); } }} package com.kgf.test;public class Run { public static void main(String[] args) throws InterruptedException { try { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(200); myThread.interrupt(); } catch (Exception e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("==========END================"); }} 通过上述代码,我们可以看到,当线程处于睡眠状态时,调用interrupt()方法会立即停止线程,并进入catch块进行处理。线程状态会被设置为false,即线程已被停止。
通过上面的代码我们可以知道,我们是先让MyThread对象线程进入到睡眠状态,然后调用interrupt()方法去停止它。从结果看,如果在睡眠状态下停止某一线程,就会使其进入catch语句,并且清除停止状态值,使其变成false。
如果我们先调用interrupt()方法,再让线程进入睡眠状态,线程不会立即停止,而是会继续运行到sleep()方法处才会停止。
package com.kgf.test;public class Run { public static void main(String[] args) throws InterruptedException { try { MyThread myThread = new MyThread(); myThread.start(); myThread.interrupt(); } catch (Exception e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("==========END================"); }} 通过上述代码可以看到,当我们先执行interrupt()方法时,MyThread线程会一直运行到sleep()方法时才会停止,不会立刻停止。
从上面结果可知,当我们先执行interrupt()方法时,MyThread线程会一直运行到sleep()方法时才进入catch语句中,不会立刻停止。
转载地址:http://cfql.baihongyu.com/