-2

我有一个函数可以迭代地进行计算并每次更新一个类全局变量(该函数运行迭代深化算法)。我想找到一种方法来进行计算,然后在 5s 后将全局变量值返回给调用者,而无需等待计算完成:

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 回答