0

我們使用ScheduledThreadPoolExecutor並在提交作業後立即調用shutdown。 因爲根據文檔關機不殺死提交的任務,運行任務並允許它完成。會工作嗎?

問題是關機後,我們可以繼續使用ScheduledThreadPoolExecutor提交的未來對象返回。

 

    private static Future submitACall(Callable callableDelegate) { 
     ScheduledThreadPoolExecutor threadPoolExe = null; 
     try { 
      threadPoolExe = new ScheduledThreadPoolExecutor(1);  
      return threadPoolExe.submit(callableDelegate); 
     } finally {  
      threadPoolExe.shutdown(); 
     } 
     } 
    //in another method... 
    if(future.isDone()) 
    future.get(); 

回答

0

是的,你可以在一個try-catch

package testsomething; 
import java.util.concurrent.Callable; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.Future; 
import java.util.concurrent.ScheduledThreadPoolExecutor; 

public class TestSomething { 
    private static Future future = null; 
    private static ScheduledThreadPoolExecutor threadPoolExe = null; 

    public static void main(String[] args) { 
     Callable callableDelegate = new MyCallable(); 
     future = submitACall(callableDelegate); 
     try { 
      System.out.println("First get: " + ((Integer)future.get())); 
     } catch (InterruptedException | ExecutionException ex) { 
      System.out.println("Exception: " + ex); 
     } 
     try { 
      Thread.sleep(100L); 
     } catch (InterruptedException ex) { 
      System.out.println("Exception: " + ex); 
     } 

     try { 
      System.out.println("Thread pool shut down? " + threadPoolExe.isShutdown()); 
      System.out.println("Second get through 'anotherMethod': " + anotherMethod()); 
     } catch (InterruptedException | ExecutionException ex) { 
      System.out.println("Exception: " + ex); 
     } 
    } 

    private static Future submitACall(Callable callableDelegate) { 
     try { 
      threadPoolExe = new ScheduledThreadPoolExecutor(1);  
      return 
       threadPoolExe.submit(callableDelegate); 
     } finally {  
      threadPoolExe.shutdown(); 
     } 
     } 
    private static Integer anotherMethod() throws ExecutionException, InterruptedException { 
     if(future.isDone()) 
      return ((Integer)future.get()); 
     else 
      return null; 
    } 

    private static class MyCallable implements Callable { 
     @Override 
     public Object call() throws Exception { 
      return new Integer(0); 
     } 
    } 
}