javafx - How to wait cancellation of task after Service#cancel? -
look @ example:
package sample; import javafx.application.application; import javafx.application.platform; import javafx.concurrent.service; import javafx.concurrent.task; import javafx.stage.stage; public class main extends application { //notice: class in **other file** (here example) private static class myservice extends service { @override protected task createtask() { return new task() { @override protected object call() throws exception { system.out.println("service: start"); while(true) { system.out.println("service: iteration"); // thread.sleep(3000); // raise interruptedexception after cancel, how such code (it won't raise exception): for(long = 0; < 1_000_000_000; i++) { } if (iscancelled()) break; } system.out.println("service: end"); return null; } }; } } @override public void start(stage primarystage) throws exception { myservice myservice = new myservice(); myservice.start(); thread.sleep(5000); myservice.cancel(); system.out.println(myservice.getstate()); // here `cancelled` task isn't finished yet. // <--- how wait cancellation of task here? system.out.println("this command must called after `service: end`"); platform.exit(); } public static void main(string[] args) { launch(args); } }
as known call of service#cancel
doesn't wait cancellation of task
. so, want block main thread , await cancellation of task
. how can it?
p.s.
looks service
doesn't provide callback/event handler check real cancellation of task
. right?
by default, service.cancel()
interrupts task. interruptedexception
must raised , task terminated (forcefully).
one thing store created task in global variable in myservice
class , override cancel method this:
class myservice extends service { private task t; @override public boolean cancel() { if (t != null) { return t.cancel(false); } else { return false; } } @override protected task createtask() { t = new task() { /* ... */ }; return t; } }
the rest easy. add change listener service state property (or use setoncanceled()
method) , whatever want after state change, in callback.
Comments
Post a Comment