Documentation

The Java™ Tutorials
Hide TOC
Canceling Background Tasks取消后台任务
Trail: Creating a GUI With Swing
Lesson: Concurrency in Swing
Section: Worker Threads and SwingWorker

Canceling Background Tasks取消后台任务

To cancel a running background task, invoke SwingWorker.cancel. 要取消正在运行的后台任务,请调用SwingWorker.cancelThe task must cooperate with its own cancellation. 任务必须与其自身的取消配合。There are two ways it can do this:有两种方法可以做到这一点:

The cancel method takes a single boolean argument. cancel方法采用单个boolean参数。If the argument is true, cancel sends the background task an interrupt. 如果参数为truecancel将向后台任务发送一个中断。Whether the argument is true or false, invoking cancel changes the cancellation status of the object to true. 无论参数是true还是false,调用cancel都会将对象的取消状态更改为trueThis is the value returned by isCancelled. 这是isCancelled返回的值。Once changed, the cancellation status cannot be changed back.一旦更改,取消状态就不能更改回原来的状态。

The Flipper example from the previous section uses the status-only idiom. 上一节中的Flipper示例使用仅状态习惯用法。The main loop in doInBackground exits when isCancelled returns true. isCancelled返回true时,doInBackground中的主循环退出。This will occur when the user clicks the "Cancel" button, triggering code that invokes cancel with an argument of false.当用户单击“Cancel”按钮,触发以false参数调用cancel的代码时,就会发生这种情况。

The status-only approach makes sense for Flipper because its implementation of SwingWorker.doInBackground does not include any code that might throw InterruptedException. 仅状态方法对Flipper来说很有意义,因为它的SwingWorker.doInBackground实现不包含任何可能引发InterruptedException的代码。To respond to an interrupt, the background task would have to invoke Thread.isInterrupted at short intervals. 为了响应中断,后台任务必须在短时间间隔内调用Thread.isInterruptedIt's just as easy to use SwingWorker.isCancelled for the same purpose同样,使用SwingWorker.isCancelled也很容易


Note: If get is invoked on a SwingWorker object after its background task has been cancelled, java.util.concurrent.CancellationException is thrown. 如果在SwingWorker对象的后台任务取消后对其调用get,则会引发java.util.concurrent.CancellationException

Previous page: Tasks that Have Interim Results
Next page: Bound Properties and Status Methods