2014-11-04 2 views
1

콘솔에서 무한 while 루프를 시작하고 중지하는 솔루션을 찾으려고합니다.무한 루프 동안 시작 및 중지

내 최선의 선택은 무엇입니까? 별도의 스레드로 작업하거나 키 이벤트 리스너와 작업 하시겠습니까? 스캐너가 해결책일지도 모르지만 스캐너가 입력을 기다리는 중입니다 ...

boolean stop = false; 
while(!stop){ 
    try { 
      ... 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
} 
+2

당신의 무한이 루프가 어떻게해야되는 동안 어떤 정교한하시기 바랍니다. –

+0

활성 mq 브로커에서 메시지를 푸시합니다. 그것은 멈추고 시작되어야합니다. – letsjak

+0

어디에서 메시지를 가져 옵니까? – isnot2bad

답변

0

뭔가 모든 경우를 포함한다 :

import java.util.Scanner; 
import java.util.logging.Logger; 

public class Testclass { 

    public static void main(String[] args) { 

     final Logger logger = Logger.getLogger(Testclass.class.getName()); 

     /* Declare a scanner to get user input... */ 
     final Scanner scanner = new Scanner(System.in); 

     /* ...and make sure it gets closed under all circumstances */ 
     Runtime.getRuntime().addShutdownHook(new Thread() { 
      @Override 
      public void run() { 
       logger.info("Closing Scanner."); 
       scanner.close(); 
      } 
     }); 

     /* Our runnable which does the actual work */ 
     Runnable runner = new Runnable() { 

      @Override 
      public void run() { 

       /* We want to run at least once */ 
       do { 

        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         logger.info("Got interrupted"); 

         /* Edit: we need to return here, as we don't want 
         * to execute the payload code in case 
         * we are interrupted. Replaces stopped variable 
         */ 
         return; 
        } 

        /* 
        * Do here whatever you want. 
        */ 
        logger.info("Doing Stuff"); 


       } while (true); 
      } 
     }; 

     /* We initialize to prevent ugly null checks */ 
     Thread t = new Thread(runner); 

     /* You can actually enter whatever you want for stopping the thread */ 
     System.out.println("Enter \"s\" to start/stop thread, \"q\" to exit"); 

     while (true) { 
      /* Blocking, our thread runs anyway if started */ 
      String input = scanner.next(); 

      if (!t.isAlive() && input.equals("s")) { 

       /* 
       * We ensure that we have a new thread because stopped threads 
       * can't be reused. 
       */ 
       t = new Thread(runner); 
       logger.info("Starting thread"); 
       t.start(); 

      } else if (t.isAlive()) { 

       /* 
       * If the thread is alive, we want to stop it on user input 
       * regardless wether it is q or s 
       */ 
       logger.info("Shutting down thread..."); 

       /* We tell the thread to shut itself down */ 
       t.interrupt(); 

       try { 
        /* We wait for our thread to finish cleanly */ 
        t.join(); 
       } catch (InterruptedException e) { 
        /* Something is severely wrong here */ 
        logger.severe("Got interrupted during thread shutdown:"); 
        e.printStackTrace(); 
        logger.severe("Unclean exit!"); 
        System.exit(5); 
       } 

       logger.info("Thread stopped"); 

      } 

      /* 
      * If the thread was running on user input 
      * it is cleanly shut down by now 
      * Next, we want to find out wether we should exit 
      * or wait for the next user input of "s" to start. 
      */ 
      if (input.equals("q")) { 
       logger.info("Exiting..."); 
       System.exit(0); 
      } 
      /* Clear the input line */ 
      scanner.nextLine(); 

     } 
    } 
} 
3

"정지 가능한"루프를 래핑하는 무한 루프가 필요합니다. 루프를 빠져 나가면 다시 입력 할 수 있어야하기 때문입니다.

+4

멈출 수있는 대신에 멈출 수있는 루프를 만들 수 있습니다 .. 예를 들어 ... 당신은 당신의 GF와 헤어지지 않지만 당신은 서로에게서 휴식을 취하고 당신이 흥분되면 다시 관계를 재개합니다. 당신은 내가 무엇을 의미하는지 안다. – letsjak

+0

@letsjak WTF는 방금 읽었다. 그렇다. 무슨 뜻인지는 알지만, 당신은 루프를 일시 정지 할 수 없다. –

+1

@letsjak http://area51.stackexchange.com/에 기여해야한다. 제안/77052/관계 –

0

이 부분을 메서드에 넣고 처음에는이 메서드를 호출 한 다음 이벤트 리스너, 시작 및 루프를 중지하기위한 특정 키를 포함 할 수 있습니다. 이 같은