-2

繰り返し計算を行い、毎回クラスのグローバル変数を更新する関数があります (関数は反復深化アルゴリズムを実行します)。計算を実行し、5 秒後に計算が完了するのを待たずにグローバル変数の値を呼び出し元に返す方法を見つけたいと考えています。

start computation
wait 5s
return global variable and terminate the computation function if not done

私は試した:

start computation in a new thread
curThread.sleep(5s)
return current global variable value and interrupt the computation thread

しかし、スレッドの終了は時々失敗します

ありがとう

4

1 に答える 1

1

これは、実際の解決策というよりもヒントのようなものです。おそらく、独自のニーズに合わせて調整する必要があります。

 class MyRunnable implements Runnable{

      private String result = "";
      private volatile boolean done = false;

      public synchronized void run(){
           while(!done){
                try{
                     Thread.sleep(1000);
                } catch (InterruptedException e) {
                     e.printStackTrace();
                }
                result = result + "A";
           }
    }

    public synchronized String getResult(){
         return result;
    }

    public void done(){
         done = true;
    }
 }

そして、それを実行するコード:

 public static void main(String[] args) throws Exception {
    MyRunnable myRunnable = new MyRunnable();
    ExecutorService service = Executors.newFixedThreadPool(1);
    service.submit(myRunnable);
    boolean isFinished = service.awaitTermination(5, TimeUnit.SECONDS);
    if(!isFinished) {
        myRunnable.done();
        String result = myRunnable.getResult();
        System.out.println(result);
    }
    service.shutdown();
}
于 2013-04-15T19:12:26.117 に答える