2014-05-16 4 views
-1

계속 DB 작업을 계속 실행하는 스레드를 시작해야하는 곳에서 스레드 스레딩 요구 사항이 있습니다. 30 초마다 실행해야하는 두 번째 스레드가 있습니다. 두 번째 스레드의 작업은 첫 번째 스레드를 죽이고 첫 번째 스레드의 새 인스턴스를 시작합니다.동시에 실행중인 스레드

나는 이것을 달성하기 위해 몇 가지 방법을 시도했지만 같은 것을 할 수는 없습니다.

public class ThreadMain { 

public static void main(String[] args) throws InterruptedException, BrokenBarrierException{ 

    final CyclicBarrier gate = new CyclicBarrier(3); 

    Thread t1 = new Thread(){ 
     public void run(){ 
      try { 
       gate.await(); 
       while(true) 
       { 
        System.out.println("Thread1"); 
        break; 

       } 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (BrokenBarrierException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     }}; 
    Thread t2 = new Thread(){ 
     public void run(){ 
      try { 
       gate.await(); 
       while(true) 
       { 
        System.out.println("Continiously running thread:-Thread2");  

       } 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (BrokenBarrierException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     }}; 

    t1.start(); 
    t2.start(); 
+4

당신의 시도를 보여줄 수 있습니까? –

+0

여러 가지 방법 중 하나를 시도해 보셨습니까? – Sanjeev

+0

안녕하세요, 위의 코드를 추가했습니다. 하지만 여기는 두 번째 스레드를 지속적으로 실행하고 있습니다 .O/P "Continiously running thread : -Thread2"입니다. 왜 첫 번째 스레드 출력이 표시되지 않는지 알지 못합니다. – RanjanPradhan

답변

0

이것은 잘 작동하는 것 같다 :

// Thread that runs forever. 
volatile static Thread forEverThread = null; 

static class ForEver implements Runnable { 

    @Override 
    public void run() { 
     try { 
      while (true) { 
       Thread.sleep(1000); 
       System.out.println("For Ever!"); 
      } 
     } catch (InterruptedException ex) { 
      // Just quit if I was interrupted. 
     } 
    } 

} 

// Stop the thread if it is running. 
private static void stopForeverThread() throws InterruptedException { 
    // Skip if non-existent. 
    if (forEverThread != null) { 
     // Make sure no-one else is already doing it. 
     synchronized (forEverThread) { 
      // Still not null? 
      if (forEverThread != null) { 
       // Interrupt it. 
       forEverThread.interrupt(); 
       // Wait for it to finish. 
       forEverThread.join(); 
       // Clear it. 
       forEverThread = null; 
      } 
     } 
    } 
} 

private static void restartForeverThread() throws InterruptedException { 
    System.out.println("Restarting..."); 
    // Stop it if it is running. 
    stopForeverThread(); 
    // Start it again. 
    forEverThread = new Thread(new ForEver()); 
    forEverThread.start(); 
    System.out.println("Restarted"); 
} 

public static void start() throws InterruptedException { 
    // Start it all up. 
    restartForeverThread(); 
    // Timed event to restart it. 
    Timer restartTimer = new Timer(true); 
    restartTimer.scheduleAtFixedRate(
      new TimerTask() { 
       @Override 
       public void run() { 
        try { 
         // Restart every few seconds. 
         restartForeverThread(); 
        } catch (InterruptedException ex) { 
         // We were interrupted during restart - Log it. 
        } 
       } 
       // Every few seconds. 
      }, 0, 10 * 1000); 

} 

public static void main(String args[]) { 
    try { 
     // Start it all up. 
     start(); 
     // Hang around for a while - to see what happens. 
     Thread.sleep(60 * 1000); 
    } catch (Throwable t) { 
     t.printStackTrace(System.err); 
    } 
} 
0

데이터베이스 작업이 인터럽트 경우, 최선의 전략은 ScheduledExecutorService을 사용하는 것입니다 (즉,이 스레드 중단에 반응하고 따라서 그 취소 할 수 있습니다) 데이터베이스 태스크 자체와 주기적으로 실행되는 재시작 태스크 모두.

작업스레드이 다른 두 가지가하는 것으로하십시오 작업가 실행해야 작품의 조각, 스레드이지만 동시에이 작업을 수행 할 수있는 메커니즘입니다. 아마 당신이 원하지 않는 것을 - 당신의 DatabaseTask 중단 스레드에 민감하지이며, 데이터베이스 동작의 수행을 진행하는 경우, 지속적으로 성장할 것입니다 데이터베이스 작업을 실행하는 스레드 수 있다는

static class DatabaseTask implements Runnable { 
    public void run() { 
     ... 
    } 
} 

static class RestartTask implements Runnable { 
    private final ExecutorService executor; 
    private volatile Future<Void> future; 

    public RestartTask(ExecutorService executor) { 
     this.executor = executor; 
    } 

    public void run() { 
     if (future != null) { 
      future.cancel(true); 
     } 
     future = executor.submit(new DatabaseTask()); 
    } 
} 

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 
executor.scheduleAtFixedRate(new RestartTask(executor), 0, 30, TimeUnit.SECONDS); 

참고. 따라서 모든 데이터베이스 작업 차단은 중단 가능하거나 적절한 시간 내에 종료되어야합니다.

관련 문제