取消后台任务
原文: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/cancel.html
要取消正在运行的后台任务,请调用 SwingWorker.cancel 任务必须配合自己的取消。有两种方法可以做到这一点:
- 通过在收到中断时终止。该程序在 Concurrency 的 Interrupts 中描述。
- 通过短时间间隔调用
SwingWorker.isCancelled。如果已为此SwingWorker调用cancel,则此方法返回true。
cancel方法采用单个boolean参数。如果参数为true,cancel会向后台任务发送中断。无论参数是true还是false,调用cancel都会将对象的取消状态更改为true。这是isCancelled返回的值。更改后,取消状态无法更改。
上一节中的Flipper示例使用仅状态惯用法。当isCancelled返回true时,doInBackground中的主循环退出。当用户单击“取消”按钮,触发使用false参数调用cancel的代码时,会发生这种情况。
仅状态方法对Flipper有意义,因为它SwingWorker.doInBackground的实现不包括任何可能抛出InterruptedException的代码。要响应中断,后台任务必须以较短的间隔调用Thread.isInterrupted。使用SwingWorker.isCancelled同样容易
Note: If get is invoked on a SwingWorker object after its background task has been cancelled, java.util.concurrent.CancellationException is thrown.
