前文从任务到线程:Java结构化并发应用程序中介绍了如何安排任务启动线程。
线程在启动之后,正常的情况下会运行到任务完成,但是有的情况下会需要提前结束任务,如用户取消操作等。可是,让线程安全、快速和可靠地停止并不是件容易的事情,因为Java中没有提供安全的机制来终止线程。虽然有Thread.stop/suspend等方法,但是这些方法存在缺陷,不能保证线程中共享数据的一致性,所以应该避免直接调用。

线程在终止的过程中,应该先进行操作来清除当前的任务,保持共享数据的一致性,然后再停止。

庆幸的是,Java中提供了中断机制,来让多线程之间相互协作,由一个进程来安全地终止另一个进程。

如果外部的代码能在某个操作正常完成之前将其设置为完成状态,则该操作为可取消的Cancellable)。

操作被取消的原因有很多,比如超时,异常,请求被取消等等。

一个可取消的任务要求必须设置取消策略,即如何取消,何时检查取消命令,以及接收到取消命令之后如何处理。

最简单的取消办法就是利用取消标志位,如下所示:

  1. public class PrimeGenerator implements Runnable {
  2. private static ExecutorService exec = Executors.newCachedThreadPool();
  3. private final List<BigInteger> primes
  4. = new ArrayList<BigInteger>();
  5. //取消标志位
  6. private volatile boolean cancelled;
  7. public void run() {
  8. BigInteger p = BigInteger.ONE;
  9. //每次在生成下一个素数时坚持是否取消
  10. //如果取消,则退出
  11. while (!cancelled) {
  12. p = p.nextProbablePrime();
  13. synchronized (this) {
  14. primes.add(p);
  15. }
  16. }
  17. }
  18. public void cancel() {
  19. cancelled = true;
  20. }
  21. public synchronized List<BigInteger> get() {
  22. return new ArrayList<BigInteger>(primes);
  23. }
  24. static List<BigInteger> aSecondOfPrimes() throws InterruptedException {
  25. PrimeGenerator generator = new PrimeGenerator();
  26. exec.execute(generator);
  27. try {
  28. SECONDS.sleep(1);
  29. } finally {
  30. generator.cancel();
  31. }
  32. return generator.get();
  33. }
  34. }

这段代码用于生成素数,并在任务运行一秒钟之后终止。其取消策略为:通过改变取消标志位取消任务,任务在每次生成下一随机素数之前检查任务是否被取消,被取消后任务将退出。

然而,该机制的最大的问题就是无法应用于拥塞方法。假设在循环中调用了拥塞方法,任务可能因拥塞而永远不会去检查取消标志位,甚至会造成永远不能停止。

为了解决拥塞方法带来的问题,就需要使用中断机制来取消任务。

虽然在Java规范中,线程的取消和中断没有必然联系,但是在实践中发现:中断是取消线程的最合理的方式

Thread类中和中断相关的方法如下:

  1. public class Thread {
  2. // 中断当前线程
  3. public void interrupt();
  4. // 判断当前线程是否被中断
  5. public boolen isInterrupt();
  6. // 清除当前线程的中断状态,并返回之前的值
  7. public static boolen interrupt();
  8. }

调用Interrupt方法并不是意味着要立刻停止目标线程,而只是传递请求中断的消息。所以对于中断操作的正确理解为:正在运行的线程收到中断请求之后,在下一个合适的时刻中断自己。

使用中断方法改进素数生成类如下:

  1. public class PrimeProducer extends Thread {
  2. private final BlockingQueue<BigInteger> queue;
  3. PrimeProducer(BlockingQueue<BigInteger> queue) {
  4. this.queue = queue;
  5. }
  6. public void run() {
  7. try {
  8. BigInteger p = BigInteger.ONE;
  9. //使用中断的方式来取消任务
  10. while (!Thread.currentThread().isInterrupted())
  11. //put方法会隐式检查并响应中断
  12. queue.put(p = p.nextProbablePrime());
  13. } catch (InterruptedException consumed) {
  14. /* 允许任务退出 */
  15. }
  16. }
  17. public void cancel() {
  18. interrupt();
  19. }
  20. }

代码中有两次检查中断请求:

  • 第一次是在循环开始前,显示检查中断请求;
  • 第二次是在put方法,该方法为拥塞的,会隐式坚持当前线程是否被中断;

和取消策略类似,可以被中断的任务也需要有中断策略:
即如何中断,合适检查中断请求,以及接收到中断请求之后如何处理。

由于每个线程拥有各自的中断策略,因此除非清楚中断对目标线程的含义,否者不要中断该线程。

正是由于以上原因,大多数拥塞的库函数在检测到中断都是抛出中断异常(InterruptedException)作为中断响应,让线程的所有者去处理,而不是去真的中断当前线程。

虽然有人质疑Java没有提供抢占式的中断机制,但是开发人员通过处理中断异常的方法,可以定制更为灵活的中断策略,从而在响应性和健壮性之间做出合理的平衡。

一般情况的中断响应方法为:

  1. 传递异常:收到中断异常之后,直接将该异常抛出;
  2. 回复中断状态:即再次调用Interrupt方法,恢复中断状态,让调用堆栈的上层能看到中断状态进而处理它。

切记,只有实现了线程中断策略的代码才能屏蔽中断请求,在常规的任务和库代码中都不应该屏蔽中断请求。中断请求是线程中断和取消的基础。

定时运行一个任务是很常见的场景,很多问题是很费时间的,就需在规定时间内完成,如果没有完成则取消任务。

以下代码就是一个定时执行任务的实例:

  1. public class TimedRun1 {
  2. private static final ScheduledExecutorService cancelExec = Executors.newScheduledThreadPool(1);
  3. public static void timedRun(Runnable r,
  4. long timeout, TimeUnit unit) {
  5. final Thread taskThread = Thread.currentThread();
  6. cancelExec.schedule(new Runnable() {
  7. public void run() {
  8. // 中断线程,
  9. // 违规,不能在不知道中断策略的前提下调用中断,
  10. // 该方法可能被任意线程调用。
  11. taskThread.interrupt();
  12. }
  13. }, timeout, unit);
  14. r.run();
  15. }
  16. }

很可惜,这是反面的例子,因为timedRun方法在不知道Runnable对象的中断策略的情况下,就中断该任务,这样会承担很大的风险。而且如果Runnable对象不支持中断, 则该定时模型就会失效。

为了解决上述问题,就需要执行任务都线程有自己的中断策略,如下:

  1. public class LaunderThrowable {
  2. public static RuntimeException launderThrowable(Throwable t) {
  3. if (t instanceof RuntimeException)
  4. return (RuntimeException) t;
  5. else if (t instanceof Error)
  6. throw (Error) t;
  7. else
  8. throw new IllegalStateException("Not unchecked", t);
  9. }
  10. }
  11. public class TimedRun2 {
  12. private static final ScheduledExecutorService cancelExec = newScheduledThreadPool(1);
  13. public static void timedRun(final Runnable r,
  14. long timeout, TimeUnit unit)
  15. throws InterruptedException {
  16. class RethrowableTask implements Runnable {
  17. private volatile Throwable t;
  18. public void run() {
  19. try {
  20. r.run();
  21. } catch (Throwable t) {
  22. //中断策略,保存当前抛出的异常,退出
  23. this.t = t;
  24. }
  25. }
  26. // 再次抛出异常
  27. void rethrow() {
  28. if (t != null)
  29. throw launderThrowable(t);
  30. }
  31. }
  32. RethrowableTask task = new RethrowableTask();
  33. final Thread taskThread = new Thread(task);
  34. //开启任务子线程
  35. taskThread.start();
  36. //定时中断任务子线程
  37. cancelExec.schedule(new Runnable() {
  38. public void run() {
  39. taskThread.interrupt();
  40. }
  41. }, timeout, unit);
  42. //限时等待任务子线程执行完毕
  43. taskThread.join(unit.toMillis(timeout));
  44. //尝试抛出task在执行中抛出到异常
  45. task.rethrow();
  46. }
  47. }

无论Runnable对象是否支持中断,RethrowableTask对象都会记录下来发生的异常信息并结束任务,并将该异常再次抛出。

Future用来管理任务的生命周期,自然也可以来取消任务,调用Future.cancel方法就是用中断请求结束任务并退出,这也是Executor的默认中断策略。

用Future实现定时任务的代码如下:

  1. public class TimedRun {
  2. private static final ExecutorService taskExec = Executors.newCachedThreadPool();
  3. public static void timedRun(Runnable r,
  4. long timeout, TimeUnit unit)
  5. throws InterruptedException {
  6. Future<?> task = taskExec.submit(r);
  7. try {
  8. task.get(timeout, unit);
  9. } catch (TimeoutException e) {
  10. // 因超时而取消任务
  11. } catch (ExecutionException e) {
  12. // 任务异常,重新抛出异常信息
  13. throw launderThrowable(e.getCause());
  14. } finally {
  15. // 如果该任务已经完成,将没有影响
  16. // 如果任务正在运行,将因为中断而被取消
  17. task.cancel(true); // interrupt if running
  18. }
  19. }
  20. }

一些的方法的拥塞是不能响应中断请求的,这类操作以I/O操作居多,但是可以让其抛出类似的异常,来停止任务:

  • Socket I/O: 关闭底层socket,所有因执行读写操作而拥塞的线程会抛出SocketException
  • 同步 I/O:大部分Channel都实现了InterruptiableChannel接口,可以响应中断请求,抛出异常ClosedByInterruptException;
  • Selector的异步 I/O:Selector执行select方法之后,再执行closewakeUp方法就会抛出异常ClosedSelectorException

以套接字为例,其利用关闭socket对象来响应异常的实例如下:

  1. public class ReaderThread extends Thread {
  2. private static final int BUFSZ = 512;
  3. private final Socket socket;
  4. private final InputStream in;
  5. public ReaderThread(Socket socket) throws IOException {
  6. this.socket = socket;
  7. this.in = socket.getInputStream();
  8. }
  9. public void interrupt() {
  10. try {
  11. // 关闭套接字
  12. // 此时in.read会抛出异常
  13. socket.close();
  14. } catch (IOException ignored) {
  15. } finally {
  16. // 正常的中断
  17. super.interrupt();
  18. }
  19. }
  20. public void run() {
  21. try {
  22. byte[] buf = new byte[BUFSZ];
  23. while (true) {
  24. int count = in.read(buf);
  25. if (count < 0)
  26. break;
  27. else if (count > 0)
  28. processBuffer(buf, count);
  29. }
  30. } catch (IOException e) {
  31. // 如果socket关闭,in.read方法将会抛出异常
  32. // 借此机会,响应中断,线程退出
  33. }
  34. }
  35. public void processBuffer(byte[] buf, int count) {
  36. }
  37. }

一个应用程序是由多个服务构成的,而每个服务会拥有多个线程为其工作。当应用程序关闭服务时,由服务来关闭其所拥有的线程。服务为了便于管理自己所拥有的线程,应该提供生命周期方来关闭这些线程。对于ExecutorService,其包含线程池,是其下属线程的拥有者,所提供的生命周期方法就是shutdownshutdownNow方法。

如果服务的生命周期大于所创建线程的生命周期,服务就应该提供生命周期方法来管理线程。

我们以日志服务为例,来说明两种关闭方式的不同。首先,如下代码是不支持关闭的日志服务,其采用多生产者-单消费者模式,生产者将日志消息放入拥塞队列中,消费者从队列中取出日志打印出来。

  1. public class LogWriter {
  2. // 拥塞队列作为缓存区
  3. private final BlockingQueue<String> queue;
  4. // 日志线程
  5. private final LoggerThread logger;
  6. // 队列大小
  7. private static final int CAPACITY = 1000;
  8. public LogWriter(Writer writer) {
  9. this.queue = new LinkedBlockingQueue<String>(CAPACITY);
  10. this.logger = new LoggerThread(writer);
  11. }
  12. public void start() {
  13. logger.start();
  14. }
  15. public void log(String msg) throws InterruptedException {
  16. queue.put(msg);
  17. }
  18. private class LoggerThread extends Thread {
  19. //线程安全的字节流
  20. private final PrintWriter writer;
  21. public LoggerThread(Writer writer) {
  22. this.writer = new PrintWriter(writer, true); // autoflush
  23. }
  24. public void run() {
  25. try {
  26. while (true)
  27. writer.println(queue.take());
  28. } catch (InterruptedException ignored) {
  29. } finally {
  30. writer.close();
  31. }
  32. }
  33. }
  34. }

如果没有终止操作,以上任务将无法停止,从而使得JVM也无法正常退出。但是,让以上的日志服务停下来其实并非难事,因为拥塞队列的take方法支持响应中断,这样直接关闭服务的方法就是强行关闭,强行关闭的方式不会去处理已经提交但还未开始执行的任务。

但是,关闭日志服务前,拥塞队列中可能还有没有及时打印出来的日志消息,所以强行关闭日志服务并不合适,需要等队列中已经存在的消息都打印完毕之后再停止,这就是平缓关闭,也就是在关闭服务时会等待已提交任务全部执行完毕之后再退出。

除此之外,在取消生产者-消费者操作时,还需要同时告知消费者和生产者相关操作已经被取消。

平缓关闭的日志服务如下,其采用了类似信号量的方式记录队列中尚未处理的消息数量。

  1. public class LogService {
  2. private final BlockingQueue<String> queue;
  3. private final LoggerThread loggerThread;
  4. private final PrintWriter writer;
  5. @GuardedBy("this") private boolean isShutdown;
  6. // 信号量 用来记录队列中消息的个数
  7. @GuardedBy("this") private int reservations;
  8. public LogService(Writer writer) {
  9. this.queue = new LinkedBlockingQueue<String>();
  10. this.loggerThread = new LoggerThread();
  11. this.writer = new PrintWriter(writer);
  12. }
  13. public void start() {
  14. loggerThread.start();
  15. }
  16. public void stop() {
  17. synchronized (this) {
  18. isShutdown = true;
  19. }
  20. loggerThread.interrupt();
  21. }
  22. public void log(String msg) throws InterruptedException {
  23. synchronized (this) {
  24. //同步方法判断是否关闭和修改信息量
  25. if (isShutdown) // 如果已关闭,则不再允许生产者将消息添加到队列,会抛出异常
  26. throw new IllegalStateException(/*...*/);
  27. //如果在工作状态,信号量增加
  28. ++reservations;
  29. }
  30. // 消息入队列;
  31. queue.put(msg);
  32. }
  33. private class LoggerThread extends Thread {
  34. public void run() {
  35. try {
  36. while (true) {
  37. try {
  38. //同步方法读取关闭状态和信息量
  39. synchronized (LogService.this) {
  40. //如果进程被关闭且队列中已经没有消息了,则消费者退出
  41. if (isShutdown && reservations == 0)
  42. break;
  43. }
  44. // 取出消息
  45. String msg = queue.take();
  46. // 消费消息前,修改信号量
  47. synchronized (LogService.this) {
  48. --reservations;
  49. }
  50. writer.println(msg);
  51. } catch (InterruptedException e) { /* retry */
  52. }
  53. }
  54. } finally {
  55. writer.close();
  56. }
  57. }
  58. }
  59. }

ExecutorService中,其提供了shutdownshutdownNow方法来分别实现平缓关闭和强制关闭:

  • shutdownNow:强制关闭,响应速度快,但是会有风险,因为有任务肯执行到一半被终止;
  • shutdown:平缓关闭,响应速度较慢,会等到全部已提交的任务执行完毕之后再退出,更为安全。

这里还需要说明下shutdownNow方法的局限性,因为强行关闭直接关闭线程,所以无法通过常规的方法获得哪些任务还没有被执行。这就会导致我们无纺知道线程的工作状态,就需要服务自身去记录任务状态。如下为示例代码:

  1. public class TrackingExecutor extends AbstractExecutorService {
  2. private final ExecutorService exec;
  3. //被取消任务的队列
  4. private final Set<Runnable> tasksCancelledAtShutdown =
  5. Collections.synchronizedSet(new HashSet<Runnable>());
  6. public TrackingExecutor(ExecutorService exec) {
  7. this.exec = exec;
  8. }
  9. public void shutdown() {
  10. exec.shutdown();
  11. }
  12. public List<Runnable> shutdownNow() {
  13. return exec.shutdownNow();
  14. }
  15. public boolean isShutdown() {
  16. return exec.isShutdown();
  17. }
  18. public boolean isTerminated() {
  19. return exec.isTerminated();
  20. }
  21. public boolean awaitTermination(long timeout, TimeUnit unit)
  22. throws InterruptedException {
  23. return exec.awaitTermination(timeout, unit);
  24. }
  25. public List<Runnable> getCancelledTasks() {
  26. if (!exec.isTerminated())
  27. throw new IllegalStateException(/*...*/);
  28. return new ArrayList<Runnable>(tasksCancelledAtShutdown);
  29. }
  30. public void execute(final Runnable runnable) {
  31. exec.execute(new Runnable() {
  32. public void run() {
  33. try {
  34. runnable.run();
  35. } finally {
  36. // 如果当前任务被中断且执行器被关闭,则将该任务加入到容器中
  37. if (isShutdown()
  38. && Thread.currentThread().isInterrupted())
  39. tasksCancelledAtShutdown.add(runnable);
  40. }
  41. }
  42. });
  43. }
  44. }

导致线程非正常终止的主要原因就是RuntimeException,其表示为不可修复的错误。一旦子线程抛出异常,该异常并不会被父线程捕获,而是会直接抛出到控制台。所以要认真处理线程中的异常,尽量设计完备的try-catch-finally代码块。

当然,异常总是会发生的,为了处理能主动解决未检测异常问题,Thread.API提供了接口UncaughtExceptionHandler

  1. public interface UncaughtExceptionHandler {
  2. void uncaughtException(Thread t, Throwable e);
  3. }

如果JVM发现一个线程因未捕获异常而退出,就会把该异常交个Thread对象设置的UncaughtExceptionHandler来处理,如果Thread对象没有设置任何异常处理器,那么默认的行为就是上面提到的抛出到控制台,在System.err中输出。

Thread对象通过setUncaughtExceptionHandler方法来设置UncaughtExceptionHandler,比如这样:

  1. public class WitchCaughtThread
  2. {
  3. public static void main(String args[])
  4. {
  5. Thread thread = new Thread(new Task());
  6. thread.setUncaughtExceptionHandler(new ExceptionHandler());
  7. thread.start();
  8. }
  9. }
  10. class ExceptionHandler implements UncaughtExceptionHandler
  11. {
  12. @Override
  13. public void uncaughtException(Thread t, Throwable e)
  14. {
  15. System.out.println("==Exception: "+e.getMessage());
  16. }
  17. }

同样可以为所有的Thread设置一个默认的UncaughtExceptionHandler,通过调用Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)方法,这是Thread的一个static方法。

下面是一个例子,即发生为捕获异常时将异常写入日志:

  1. public class UEHLogger implements Thread.UncaughtExceptionHandler {
  2. // 将未知的错误计入到日志中
  3. public void uncaughtException(Thread t, Throwable e) {
  4. Logger logger = Logger.getAnonymousLogger();
  5. logger.log(Level.SEVERE, "Thread terminated with exception: " + t.getName(), e);
  6. }
  7. }

Executor框架中,需要将异常的捕获封装到Runnable或者Callable中并通过execute提交的任务,才能将它抛出的异常交给UncaughtExceptionHandler,而通过submit提交的任务,无论是抛出的未检测异常还是已检查异常,都将被认为是任务返回状态的一部分。如果一个由submit提交的任务由于抛出了异常而结束,那么这个异常将被Future.get封装在ExecutionException中重新抛出。

  1. public class ExecuteCaught
  2. {
  3. public static void main(String[] args)
  4. {
  5. ExecutorService exec = Executors.newCachedThreadPool();
  6. exec.execute(new ThreadPoolTask());
  7. exec.shutdown();
  8. }
  9. }
  10. class ThreadPoolTask implements Runnable
  11. {
  12. @Override
  13. public void run()
  14. {
  15. Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
  16. System.out.println(3/2);
  17. System.out.println(3/0);
  18. System.out.println(3/1);
  19. }
  20. }

扩展阅读:

  1. 多线程安全性:每个人都在谈,但是不是每个人都谈地清
  2. 对象共享:Java并发环境中的烦心事
  3. 从Java内存模型角度理解安全初始化
  4. 从任务到线程:Java结构化并发应用程序

作者:登高且赋
链接:https://www.jianshu.com/p/613286f4245e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

版权声明:本文为ZhYQ-Note原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/ZhYQ-Note/articles/10184131.html