2017-12-27 5 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

대단히 감사합니다! –

관련 문제