线程停止

来源:互联网 发布:ug编程教程百度云 编辑:程序博客网 时间:2024/05/21 22:22

大多数停止一个线程的操作使用Thread.interrupt()方法,尽管方法的名称是“停止”的意思。但是这个方法不会终止一个正在运行的线程,还需要假如一个判断才可以完成线程的停止。

利用异常可以停止线程

package com.eroadsf.thread;public class MyThread extends Thread {    @Override    public void run() {        super.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("不好意思还活着");        } catch (InterruptedException e) {            System.out.println("进Mythread.java 类run方法中的catch了");            e.printStackTrace();        }    }}
package com.eroadsf.thread;public class Run {    public static void main(String[] args)  {        try {            MyThread thread=new MyThread();            thread.start();            Thread.sleep(1000);            //interrupt 打一个停止的标记            thread.interrupt();        } catch (InterruptedException e) {            System.out.println("main catch");            e.printStackTrace();        }    }}
原创粉丝点击