2011-06-23 40 views

回答

4

您可以使用ExecutorService異步運行任務,獲得Future,使您可以在任務完成時獲取任務結果。在Future上有一個get方法,您可以打電話等待答案,並有一個超時。如果超時,則嘗試通過在Future上調用cancel來取消該任務。

ExecutorService executorService = Executors.newSingleThreadExecutor(); 

// Callable that has a run() method that executes the task 
Callable<String> callable = ...; 

// Submit the task for execution 
Future<String> future = executorService.submit(callable); 

try { 
    String result = future.get(30, TimeUnit.SECONDS); 
    System.out.println("Result: " + result); 
} 
catch (TimeoutException e) { 
    System.out.println("Timeout"); 
    future.cancel(true); 
} 

併發API還有很多,請參閱軟件包java.util.concurrent

0

你能描述一下你究竟想要什麼嗎? 只需停止執行方法,您可以使用return, System.exit(),上次停止虛擬機。 按時間檢查時間並從方法返回。此外,你可以嘗試一些反思黑客... 順便說一句,這些只是一個想象力,如果你會用更多的話來描述你需要什麼,我會幫助你。

+0

新的設計是否適合您? –

+0

對於此描述回答否如果一個線程中有兩個方法,並且如果B是新線程,則返回YES。 –

0

嘗試:

public static void wait(int n){ 
    long time0,time1; 
    time0=System.currentTimeMillis(); 
    do{ 
     time1=System.currentTimeMillis(); 
    } 
    while (time1-time0<n); 

}

我認爲作品。如果您調用此方法,請將它傳遞給需要程序等待參數的時間量(以毫秒爲單位)。

祝你好運!