2013-04-15 39 views
-2

我有一個迭代執行計算並每次更新一個類全局變量(函數運行迭代加深算法)的函數。我想找到一種方法做計算,然後返回5S給調用者後,全局變量的值,而無需等待計算完成:超時後的Java返回值

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 

但線程終止有時甚至不能

感謝

+0

你嘗試過什麼?你讀過什麼文件。你需要展示一些工作。這不是你的研究助攻。 – Gray

回答

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(); 
} 
+0

我已經嘗試過,但我的問題是,check -while(!done) - 是在函數的開始處完成的,函數體執行大量計算並修改了一些我不想在超時後發生的數據。解決這個問題的方法是在函數內的多個點檢查變量'done'。我正在考慮是否有安全的方法來立即中斷線程。 – Mouhyi

+0

@Mouhyi當然有。只要中斷線程並抓住它。看看56個特別的問題。 – Eugene