本文共 2863 字,大约阅读时间需要 9 分钟。
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); //此方法代表 让当前线程休眠 1 秒,即表示使 main线程休眠 1秒 myThread.interrupt();//调用停止线程类的方法 } catch (Exception e) { e.printStackTrace(); } System.out.println("==========END================"); }}
先sleep再用interrupt()停止 ⑴创建继承Thread类的线程类MyThread.java
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================"); }}
⑶效果:
⑷结果分析 通过上面的代码我们可知,我们是先让MyThread对象线程进入到睡眠状态,然后 我们再调用interrupt()方法去停止它。从结果看,如果在sleep状态下停止某一线程, 就会使其进入catch语句,并且清除停止状态值,使其变成false.
先interrupt()停止再sleep ⑴创建继承Thread类的线程类MyThread.java
package com.kgf.test;public class MyThread extends Thread { @Override public void run() { try { for (int i = 0; i < 500000; i++) { System.out.println("i="+(i+1)); } System.out.println("===run begin====="); Thread.sleep(200000); System.out.println("===run end====="); } catch (Exception e) { System.out.println("先停止!再遇到了sleep!进入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(); myThread.interrupt();//调用停止线程类的方法 } catch (Exception e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("==========END================"); }}
⑶效果
⑷结果分析 从上面结果可知,当我们先执行interrupt()方法时,myThread线程会一直运行到sleep()方法 时才进入catch语句中,不会立刻停止。
转载地址:http://cfql.baihongyu.com/