|
NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems
ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en:
http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com. |
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂtulo en concreto puede realizar una donación directa mediante Paypal:
|
To cancel a running background task, invokeSwingWorker.cancelThe task must cooperate with its own cancellation. There are two ways it can do this:
- By terminating when it receives an interrupt. This procedures is described in Interrupts in Concurrency.
- By invoking
SwingWorker.isCanceledat short intervals. This method returnstrueifcancelhas been invoked for thisSwingWorker.The
cancelmethod takes a singlebooleanargument. If the argument istrue,cancelsends the background task an interrupt. Whether the argument istrueorfalse, invokingcancelchanges the cancellation status of the object totrue. This is the value returned byisCanceled. Once changed, the cancellation status cannot be changed back.The
Flipperexample from the previous section uses the status-only idiom. The main loop indoInBackgroundexits whenisCancelledreturnstrue. This will occur when the user clicks the "Cancel" button, triggering code that invokescancelwith an argument offalse.The status-only approach makes sense for
Flipperbecause its implementation ofSwingWorker.doInBackgrounddoes not include any code that might throwInterruptedException. To respond to an interrupt, the background task would have to invokeThread.isInterruptedat short intervals. It's just as easy to useSwingWorker.isCancelledfor the same purpose
Note: Ifgetis invoked on aSwingWorkerobject after its background task has been cancelled,java.util.concurrent.CancellationExceptionis thrown.