Why the Task<v> Don't start again?</v>
-
I need the task to stop when the pause method is challenged, and when the conditions are met, if (ChoiceRe.getText()=="Only" it is renewed. But this code doesn't do it.
if(ChoiceRe.getText()=="Обычный"){ System.out.println("Обычный режим запущен"); normalTime=normalTime*60000; normalTime=normalTime/100; f=new FileInputStream("src//application//res//Re//NormalRe//NormalReChild.mp3"); if(pause==true){ task3 = new Task<Void>() {
@Override public Void call() throws Exception { double TimeStart = 0d; for (int row = 0; row < 100; row++) { TimeStart = TimeStart + 0.01; updateProgress(TimeStart, 1); try { Thread.sleep(normalTime); } catch (InterruptedException e) { return null; } } return null; } }; time.progressProperty().bind(task3.progressProperty()); Executors.newCachedThreadPool().submit(task3); pause=false; } else { task = new Task<Void>() { @Override public Void call() throws Exception { double TimeStart = 0d; for (int row = 0; row < 100; row++) { TimeStart = TimeStart + 0.01; updateProgress(TimeStart, 1); try { Thread.sleep(normalTime); } catch (InterruptedException e) { return null; } } return null; } }; time.progressProperty().bind(task.progressProperty()); Executors.newCachedThreadPool().submit(task); } Task<Void> task2 = new Task<Void>() { @Override protected Void call() throws Exception { while(time.getProgress()!=1.0){ if(time.getProgress()==0.03){ try { Player p=new Player(f); p.play(); } catch (JavaLayerException e) {} } } return null; } }; Executors.newCachedThreadPool().submit(task2); }
}
public void pause(){
task.cancel(true);
pause=true;
}
-
In order to resume some kind of work, we need to keep this job somewhere. As you say, the job is to change.
ProgressIndicator
which keeps its own condition, so it can be done:if ( !pause ) { // первый запуск? // сбрасываем индикатор до 0 time.progressProperty().unbind(); time.progressProperty().set( 0.0 ); }
task = new Task<Void>() { // создаем новое задание
// берем текущее состояние ProgressIndicator
double TimeStart = time.getProgress();
{
// обновляем начальный прогресс задания,
// чтобы не дернуть индикатор в bind
updateProgress(TimeStart, 1);
}@Override public Void call() throws Exception { try { // пока не доработали до 1.0, увеличиваем, обновляем прогресс, спим. while( TimeStart < 1 ) { TimeStart = TimeStart + 0.01; updateProgress(TimeStart, 1); Thread.sleep(normalTime); } // если придет InterruptedException (от task.cancel()), вываливаемся из цикла } catch (InterruptedException e) { /* e.printStackTrace(); */ } return null; }
};
time.progressProperty().bind(task.progressProperty());// не надо плодить новый ExecutorService на каждый чих, лучше
// создать 1 и обращаться к нему по необходимости
executor.submit(task);
pause = false;
Pause:
public void pause() {
// отмена - отвязываем индикатор от таска
time.progressProperty().unbind();
task.cancel(); // отменяем таск
pause = true;
}