正确停止 Java 线程

原则

使用 interrupt 来通知,而不是强制。

需要停止的线程可能不是别人写的程序,正确的做法是通知别人停下来,而不是强制。因为别人是线程的开发者,他自己更清楚线程里做了什么,什么情况下可以停,什么情况下不能停。

当我们写的线程被别人停止时应该怎么善后

当我们的线程收到停止的通知后,具体的善后工作和业务有关,下面这些情况起引导作用。

普通情况一:线程不能被停止

我们是线程的开发者,我们清楚这个线程能不能执行到一半中断(谨慎使用)。假如线程不能被中断,那么就不对 interrupt 做响应。

public class RightWayStopThreadWithoutSleep implements Runnable {
    @Override
    public void run() {
        int num = 0;

        while (num < Integer.MAX_VALUE / 2) {
            if (num % 10000 == 0) {
                System.out.println(num + "是 10000 的倍数");
            }
            num++;
        }
        System.out.println("任务执行结束");
    }

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

普通情况二:线程能被中断

使用 Thread.currentThread().isInterrupted() 可以判断线程是不是收到中断请求。

public class RightWayStopThreadWithoutSleep implements Runnable {
    @Override
    public void run() {
        int num = 0;

        while (num < Integer.MAX_VALUE / 2 && !Thread.currentThread().isInterrupted()) {
            if (num % 10000 == 0) {
                System.out.println(num + "是 10000 的倍数");
            }
            num++;
        }
        System.out.println("任务执行结束");
    }

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

阻塞情况一:线程阻塞的时候收到中断通知

当线程在阻塞的时候被中断,会抛出 InterruptedException 异常。

public class RightWayStopThreadWithSleep {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {

                while (num <= 300) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是一百的倍数");
                    }
                    num++;
                }

                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}

阻塞情况二:线程每次迭代后都阻塞

如果线程在循环里都可能被阻塞,不需要使用 Thread.currentThread().isInterrupted() 来判断是否中断。

public class RightWayStopThreadWithSleepEveryLoop {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (num <= 10000) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    num++;
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }
}

阻塞情况三:中断发生在迭代里

这个情况与上面的情况不同的是,上面在迭代外面抛出的异常,而这个是在迭代里面抛出的异常。

java 语言在设计 sleep 函数的时候,当响应了中断,就会把线程的 interrupt 标记为给清除。下面这种情况,抛出了 InterruptedException 之后,标记为被清除了,所以即使在 while 中加了是否中断的判断也没用。

public class CantInterrupt {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            while (num < 10000 && !Thread.currentThread().isInterrupted()) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍数");
                }
                num++;

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

开发中的两种最佳实践

优先选择:传递中断

throwInMethod 方法中会抛出异常,这时候要抛出来,由调用者来处理因为 throwInMethod 不知道调用者的异常处理逻辑,如果贸然 try/catch 掉,调用者就拿不到异常。

public class RightWayStopThreadInProd implements Runnable {
    @Override
    public void run() {
        while (true) {
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                // 保存日志,停止程序等等
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
        Thread.sleep(1000);
    }

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

不想或无法传递的时候:恢复中断

当 reInterrupt 拿到中断的时候,再将中断重新设置好,在调用者那里进行判断。

public class RightWayStopThreadInProd2 implements Runnable {
    @Override
    public void run() {
        while (true) {
            if(Thread.currentThread().isInterrupted()){
                System.out.println("收到中断");
                break;
            }
            reInterrupt();
        }
    }

    private void reInterrupt() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }

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

判断是否被中断相关方法

  • Thread 中的 static boolean interrupted()
    判断当先线程是否中断,不是判断调用它的线程。会清除线程中断状态。
    例如:以下两种方法判断的都是主线程是否中断,而不是 thread 线程。

    Thread thread1 = new Thread();
    System.out.println(Thread.interrupted());
    System.out.println(thread1.interrupted());
    
  • Thread 中的 boolean isInterrupted()
    判断调用它的线程是否中断。不会清除线程中断状态。

能够响应中断的方法

  • Object.wait() / wait(long timeout) / wait(long timeout, int nanos)
  • Thread.sleep(long millis) / sleep(long millis, int nanos)
  • Thread.join() / join(long millis) / join(long millis, int nanos)
  • java.util.concurrent.BlockingQueue.take()/put(Object o)
  • java.util.concurrent.locks.Lock.lockInterruptibly()
  • java.util.concurrent.CountDownLatch.await()
  • java.util.concurrent.CyclicBarrier.await()
  • java.util.concurrent.Exchanger.exchange(V)
  • java.nio.channels.InterruptibleChannel 相关方法
  • java.nio.channels.Selector 相关方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。