如何停止一个正在运行的线程?

设置flag

主线程修改flag之后确保子线程能感知到改变,然后子线程跳出循环

public class Main {
    static volatile boolean flag = true;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("start");
            while (flag) {

            }
            System.out.println("end");
        });
        thread.start();

        Thread.sleep(3000);
        flag = false;
    }
}

使用stop

不推荐使用

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("start");
            while (true) {

            }
        });
        thread.start();

        Thread.sleep(3000);
        thread.stop();
    }
}

使用interrupt

无阻塞情况

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("start");
            while (true) {
                //子线程内部没有阻塞(使用sleep),则调用thread.interrupt()之后,打断标志已经被设置为true。
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
            }
            System.out.println("end");
        });
        thread.start();

        Thread.sleep(3000);
        thread.interrupt();
    }
}

阻塞情况

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("start");
        Thread thread = new Thread(() -> {
            while (true) {
                //sleep造成阻塞,调用thread.interrupt()不会把打断标志置为true,而是抛出打断异常,所以需要在捕获异常处再次调用一次打断
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                    System.out.println("...");
                } catch (InterruptedException e) {
                    System.err.println(e.getMessage());
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println("end");
        });
        thread.start();

        Thread.sleep(3000);
        thread.interrupt();
    }

 


版权声明:本文为qq_32182637原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。