(Java多线程系列四)停止线程

停止线程

停止线程的思路

①使用退出标志,使线程正常退出,也就是当run()方法结束后线程终止。

class Thread01 extends Thread {

    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                // 可能发生异常的操作
                System.out.println(getName() + "线程一直在运行。。。");
            } catch (Exception e) {
                System.out.println(e.getMessage());
                this.stopThread();
            }
        }
    }

    public void stopThread() {
        System.out.println("线程停止运行。。。");
        this.flag = false;
    }
}

public class StopThreadDemo01 {

    public static void main(String[] args) {
        Thread01 thread01 = new Thread01();
        thread01.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread01.stopThread();
    }
}

②使用stop()方法强行终止线程,这个方法已经被弃用了,所以这里不写。

③使用interrupt()方法中断线程(只有线程在waitsleep才会捕获InterruptedException异常,执行终止线程的逻辑,在运行中不会捕获)

class Thread02 extends Thread {
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            synchronized (this) {
//                try {
//                    wait();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    this.stopThread();
//                }

                try {
                    sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    this.stopThread();
                }
            }
        }
    }

    public void stopThread() {
        System.out.println("线程已经退出。。。");
        this.flag = false;
    }
}

public class StopThreadDemo02 {

    public static void main(String[] args) {
        Thread02 thread02 = new Thread02();
        thread02.start();
        System.out.println("线程开始");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread02.interrupt();
    }
}

调用interrupt()方法会抛出InterruptedException异常,捕获后再做停止线程的逻辑即可。

Image 中断线程

如果线程处于类似while(true)运行的状态,interrupt()方法无法中断线程。

源码地址

猜你喜欢

转载自www.cnblogs.com/3LittleStones/p/12090613.html