如何结束一个线程

1. 使用stop方法结束线程

Thread的stop方法已经弃用
stop不管线程现在处于什么状态,都会直接将线程停止。
若是线程正持有一把锁,stop方法将直接释放锁,并不做任何善后的操作。
比如获得锁之后的操作是修改a的值然后修改b的值,然后再释放锁。若是在修改a的值之后被stop了,则锁被释放并且b的值并没有被修改。容易造成数据不一致的问题。

public class StopThread {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("new thread go on");
                sleep(1);
            }
        });

        t.start();
        sleep(5);
        t.stop();
    }

    private static void sleep(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

2.暂停suspend和继续resume

也是被废弃的方法,不建议使用,当线程持有一把锁,若是被suspend暂停了,他是不会释放锁的,若是忘记继续了,则锁将永远不被释放,会造成死锁的问题。

public class StopThread {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                System.out.println("new thread go on");
                sleep(1);
            }
        });

        t.start();
        sleep(5);
        t.suspend();
        sleep(5);
        t.resume();
    }

    private static void sleep(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

3. volatile结束线程

时间上很难控制,如下的while循环中不能确定执行多少次。若是在某一次的循环中阻塞,直到下一次判断状态时才能停止。
特定场景下的优雅的解决方案。

public class StopThread {
    private static volatile boolean running = true;
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            int i = 0;
            while (running) {
                i++;
                System.out.println("new thread go on:  "+i);
            }
        });
        t.start();
        sleep(1);
        running = false;
    }

    private static void sleep(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

4. interrupt结束线程

更加优雅一点,若是线程处于sleep和wait状态,可以由interruptException控制结束

public class StopThread {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (Thread.interrupted()) {
                //do something
            }
        });
        t.start();
        sleep(1);
        t.interrupt();
    }

    private static void sleep(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

猜你喜欢

转载自juejin.im/post/7078341915791327240