超时后Java返回值

时间:2013-04-15 18:27:57

标签: java multithreading timer

我有一个迭代执行计算的函数,每次都更新一个类全局变量(该函数运行迭代深化算法)。我想找到一种方法来进行计算,然后在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

但是线程终止有时会失败

由于

1 个答案:

答案 0 :(得分: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();
}