java - How one can pause and/or stop javafx.concurrent.Task? -


say, i've got javafx.concurrent.task nested thread, ie.:

task task = new task(); thread thread = new thread(task); thread.start(); 

how can in situation pause and/or stop executing task nad resume work?

there no easy way, except using deprecated suspend() , resume() methods on thread class.

in case sure task doesn't enter synchronized code work

otherwise have have halt points in task check if task has been halted , if call wait() on object block thread. call notify on object wake thread , resume. below chunk of pseudo code approach.

note work expected need check halt variable in task code.

class mytask{     volatile boolean halt = false;     object o  = new object();     public void run(){         while(notdone) {             if (halt) halt();          }     }      private halt(){         synchronized (o){o.wait()}     }       public resume(){         halt = false;         synchronized (o){o.notify()}     }     public suspend(){         halt=true;     } } 

import java.io.ioexception; public class testthread {  static class pausablerunnable implements runnable{     volatile boolean shouldhalt = false;     private final object lock=new object();     public void run(){         while(true){             if(shouldhalt)halt();             try {                 thread.sleep(500);             } catch (interruptedexception e) {                 e.printstacktrace();             }             system.out.print(".");         }     }     private void halt(){         synchronized (lock){             try {                 lock.wait();             } catch (interruptedexception e) {                 e.printstacktrace();             }         }     }       void pause(){         shouldhalt = true;     }      void resume(){         synchronized (lock){             shouldhalt=false;             lock.notify();         }     } }  public static void maipn(string[] args) throws ioexception {     pausablerunnable pr = new pausablerunnable();     thread t = new thread(pr);     t.start();      while(true) {         char c = (char) system.in.read();         if (c == 'p') {             system.out.println("pausing");             pr.pause();         }         if (c == 'r') {             system.out.println("resuming");             pr.resume();         }     } } } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -