2016-09-21 754 views
0

我有2個類。一個POJO和主。ExecutorService.awaitTermination(超時,單位)即使在超時後仍繼續運行

POJO類

public class Processor implements Runnable{ 

private int id; 

public Processor(int id) 
{ 
    this.id = id; 

} 
@Override 
public void run() { 
    System.out.println("Started ...."+ id); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    System.out.println("Stoped ..." + id); 
} 

} 

主類

public class Main { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    ExecutorService executor = Executors.newFixedThreadPool(2); 
    for(int i = 0; i < 5;i++) 
    { 
     executor.submit(new Processor(i)); 


    } 
    executor.shutdown(); 
    System.out.println("All tasks Submits"); 
    try { 
     executor.awaitTermination(1, TimeUnit.MILLISECONDS); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("Intrupted or Timeout"); 

    } 
    System.out.println("all Tasks completed"); 
} 

}

當我運行這段代碼我得到的

Started ....0 
All tasks Submits 
Started ....1 
all Tasks completed 
Stoped ...1 
Started ....2 
Stoped ...0 
Started ....3 
Stoped ...2 
Started ....4 
Stoped ...3 
Stoped ...4 

的輸出,但按我的理解一次一次發生它應該引發中斷的異常並返回。但是爲什麼它在TRY塊退出後仍然繼續運行。

回答

1

讓轉向的Javadoc awaitTermination

阻塞,直到所有任務都關機請求後完成執行,或發生超時,或者當前線程中斷,無論哪一個首先發生。

換句話說:調用該方法並不意味着已經提交的作業不再被執行。所以這個缺陷在你的假設之內。

您的主要運行到該超時,但僅僅因爲您然後打印「所有任務完成」並不表示真實的說法。那些提交的任務在完成時完成。而不是之前!

所以,如果你想真的「停止」一切,你應該嘗試用shutdownNow來代替。

1

正如@GhostCat說,awaitTermination被阻塞的線程在給定的時間,如果你想引起異常而阻塞,你可以做這樣的一擊:

Thread t = new Thread(){ 
    public void run() { 
    ExecutorService exec = Executors.newCachedThreadPool(); 
    exec.execute(new Runnable() { 
     @Override 
     public void run() { 
     System.out.println("start ..."); 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
     } 
     System.out.println("end ..."); 
     } 
    }); 

    exec.shutdown(); 

    try { 
     exec.awaitTermination(100, TimeUnit.MILLISECONDS); 
    } catch (Exception e) { 
     System.out.println("awaitTermination"); 
    } 
    System.out.println("main ended"); 
    }; 
}; 
t.start(); 
Thread.sleep(10);; 
t.interrupt(); 

運行這段代碼的主要方法。