并发编程---- 如何让线程安全的停止工作

常用让线程停止工作的 API
  • stop() :终结一个线程的时候,无法保证资源释放。
  • suspend() :线程不会释放资源。其他线程拿不到资源,容易出现死锁问题。
  • interrupt() :中断一个线程。并不是强行关闭这个线程,打个招呼。中断标志位 置为 true
  • isInterrupted() :判断当前线程是否处于中断状态 判读中断标志位 是否为 true
  • static 的 isInterrupted()方法 :判断当前线程是否处于中断状态,会把中断标志位 改为 false
继承Thread 使用 interrupt 中断线程:
public class EndThread {

    private static class UseThread extends Thread {

        public UseThread(String name) {
            super(name);
        }

        public void run() {
            String name = Thread.currentThread().getName();
            while (!isInterrupted()) {
                System.out.println(name + " is run");
            }
            System.out.println(name + " isInterrupted flag is " + isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        UseThread endThread = new UseThread("endThread");
        endThread.start();
        Thread.sleep(20);
        endThread.interrupt();
    }
}
实现 Runnable 使用 interrupt 中断线程:
public class EndRunnable {

    private static class UseRunnable implements Runnable {

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(name + " is run");
            }
            System.out.println(name + " isInterrupted flag is " + Thread.currentThread().isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        UseRunnable useRunnable = new UseRunnable();
        Thread thread = new Thread(useRunnable);
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }

}

注意:方法抛出 InterruptedException 的时候,会把线程的中断标志位会被复位成 false

你可能感兴趣的:(多线程)