2017-07-21 22 views
0

イムはかなり新しいJavaで、私はそれに直面する必要があるという問題があります。私がこれを行う場合:スケジュールされたすべてのタスクが終了した後に何かを行うには?

//somecode 
double number=0; 
Timer timer = new Timer(); 
timer.schedule(new someFunction(),0,1); 

このスケジュールが完了した後で、何か他のことをすることができますか?

私はこれがしようとした場合:

//somecode 
double number=0; 
Timer timer = new Timer(); 
timer.schedule(new someFunction(),0,1); 
number=1; 

数の変化は、タスクの終了前に発生します。これを解決する方法はありますか?

import java.util.Timer; 
import java.util.TimerTask; 


public class Main { 


    public static void main(String[ ] args) { 

     class SomeTask extends TimerTask { 

      private double someVariable; 
      public SomeTask(double someVariable){ 
       this.someVariable=someVariable; 

      } 


      public void run() { 

       while(this.someVariable<10){ 
        this.someVariable++; 
        System.out.println(this.someVariable); 
       } 
       this.cancel(); 
      } 
     } 


     boolean allTaskDone=false; 

     double someVariable=0; 

     Timer timer = new Timer(); 
     timer.schedule(new SomeTask(someVariable),0,1000); 

     allTaskDone=true; 
     System.out.println(allTaskDone); 


    } 
} 

出力は次のとおりです:

true 
1.0 
2.0 
3.0 
4.0 
5.0 
6.0 
7.0 
8.0 
9.0 
10.0 

どのように私は、タスクがcompleatedされた後allTask​​Doneが評価されることができます私は私の質問を良く公開するために、機能のコードを書きましたの?言い換えれば、次のようなことを起こしてください。

1.0 
2.0 
3.0 
4.0 
5.0 
6.0 
7.0 
8.0 
9.0 
10.0 
true 

ありがとうございました!

+0

スケジュールされたタスクのすべての後ですか?またはスケジュールされたタスクのたびに? –

+0

有効な[mcve]はあなたのコードとあなたの質問を明確にするのに役立ちます。 –

+0

私はあなたの問題を正しく理解していれば、あなたはあなたの作品をシリアライズしています。タイマーは単なる気晴らしです。最初の質問に答える – efekctive

答えて

0

timer.schedule(new someFunction()、0,1)の1。 1msごとにあなたの仕事を繰り返すことを意味します。

次のコードは、あなたのやり取りを模倣し、あなたがしたいことをします。私はTimerの代わりにScheduledExecutorServiceを使用しています。

final FutureTask<String> task = new FutureTask<String>(new Callable<String>() { 
     public String call() throws Exception { 
      int counter = 0; 
      boolean finished = false; 
      while (!finished) { 
       System.out.println("work in progress..." + counter); 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       counter += 1; 
       if (counter > 5) { 
        finished = true; 
        return "work done"; 
       } 
      } 
      return "not finished"; 
     } 
    }); 

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
    scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.MILLISECONDS); 
    String done = task.get(); 
    scheduler.shutdown(); 
    System.out.println(done); 
+0

ありがとうございます!それはまさに私が望んでいたものです! –

+0

Laurent、あなたのソリューションは私が尋ねたことをしますが、Timeクラスを使ってこれを行う方法がありますか? timertaskだけでJFreechartのlineChartが動的に変更できるので、これを特に使用する必要があります。 –

+0

あなたのallTask​​Doneはタスク自身によって更新されなければなりません。マップに虚偽の値が残っていない場合は、キータスクUUID一意識別子、ブール値taskIsDone、および火災のみallTask​​Done = trueのマップを参照するか、Consumer(メインループ)/ Producer(それぞれ)のBlockingQueueを使用します。タスク)とloop.take()のループはhttp://www.journaldev.com/1034/java-blockingqueue-exampleに記載されています –