Java 停止线程

2018-08-16  本文已影响27人  凯玲之恋

1概述

在Java中有以下3种方法可以终止正在运行的线程:

2 stop()方法停止线程

    try {
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(8000);
            thread.stop();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

3 调用interrupt()方法来停止线程

3.1 this.interrupted() VS this.isInterrupted()

3.2 interrupt方法配合抛出异常停止线程

建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止的事件得以传播。
【Java 多线程】Java中主线程如何捕获子线程抛出的异常

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("我在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(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}
qq_pic_merged_1534415736719.jpg

3.3 interrupt方法 配合 return 停止线程

程序正常执行完成,线程退出。

public class MyThread extends Thread {
    @Override
    public void run() {
            while (true) {
                if (this.isInterrupted()) {
                    System.out.println("停止了!");
                    return;
                }
                System.out.println("timer=" + System.currentTimeMillis());
            }
    }
}

public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyThread t=new MyThread();
        t.start();
        Thread.sleep(2000);
        t.interrupt();
    }
}
qq_pic_merged_1534415883582.jpg

3.4 注意

参考

《java多线程编程核心技术》

上一篇 下一篇

猜你喜欢

热点阅读