2017-12-27 1759 views
0

我的程序應該在多線程中運行很長時間。 我需要爲線程設置超時的能力,一旦線程終止,我想再次啓動它。 這裏是我的代碼:如何爲Executors.newFixedThreadPool設置超時時間,並在達到超時時創建線程

@Test 
    public void testB() throws InterruptedException { 
     final ExecutorService threadPool = Executors.newFixedThreadPool(2); 
     for(int i=0; i<2; i++){ 
      threadPool.submit(new Runnable() { 
       public void run() { 
         System.out.println("thread start: " + Thread.currentThread().getName()); 
        try { 
         Thread.sleep(5000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 

       } 
      }); 
     } 
     threadPool.shutdown(); 
     threadPool.awaitTermination(100000, TimeUnit.SECONDS); 
    } 
+0

所以你想要做的是一遍又一遍地運行相同的任務,直到達到給定的超時? – Ward

+0

是的。如果在其中一個線程上達到超時,那麼我需要執行另一個線程。例如 - 我需要2一直運行2線程 –

回答

1

下面的代碼會一遍又一遍地運行相同的任務。 游泳池將在一定時間後關閉。

這似乎是做你的要求。

final ExecutorService threadPool = Executors.newFixedThreadPool(2); 

for(int i = 0; i < 2; i++){ 
    final int taskNb = i; 
    threadPool.submit(new Runnable() { 
     public void run() { 
      System.out.println("Thread " + taskNb + " start: " + Thread.currentThread().getName()); 
      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      // Submit same task again 
      threadPool.submit(this); 

     } 
    }); 
} 

// Only shutdown the pool after given amount of time 
Thread.sleep(100_000_000); 
threadPool.shutdown(); 

// Wait for running tasks to finish 
threadPool.awaitTermination(5, TimeUnit.SECONDS); 
+0

非常感謝你! –