取消后台任务
原文: 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.