The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
To cancel a running background task, invoke 要取消正在运行的后台任务,请调用SwingWorker.cancel
. SwingWorker.cancel
。The task must cooperate with its own cancellation. 任务必须与其自身的取消配合。There are two ways it can do this:有两种方法可以做到这一点:
SwingWorker.isCancelled
at short intervals. SwingWorker.isCancelled
。true
if cancel
has been invoked for this SwingWorker
.SwingWorker
调用cancel
,则此方法返回true
。The cancel
method takes a single boolean
argument. cancel
方法采用单个boolean
参数。If the argument is 如果参数为true
, cancel
sends the background task an interrupt. true
,cancel
将向后台任务发送一个中断。Whether the argument is 无论参数是true
or false
, invoking cancel
changes the cancellation status of the object to true
. true
还是false
,调用cancel
都会将对象的取消状态更改为true
。This 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”按钮,触发以cancel
with an argument of false
.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.isInterrupted
。It's just as easy to use 同样,使用SwingWorker.isCancelled
for the same purposeSwingWorker.isCancelled
也很容易
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
。