Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 启动和停止无限while循环_Java_Multithreading_Thread Sleep - Fatal编程技术网

Java 启动和停止无限while循环

Java 启动和停止无限while循环,java,multithreading,thread-sleep,Java,Multithreading,Thread Sleep,我试图找到一个解决方案来启动和停止控制台中的无限while循环 我最好的选择是什么?使用单独的线程还是使用键事件侦听器?扫描仪可能是一个解决方案,但扫描仪等待输入 boolean stop = false; while(!stop){ try { ... Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } 您将需要一个无

我试图找到一个解决方案来启动和停止控制台中的无限while循环

我最好的选择是什么?使用单独的线程还是使用键事件侦听器?扫描仪可能是一个解决方案,但扫描仪等待输入

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

您将需要一个无限循环来包装您的“可停止”循环。因为一旦你离开循环,你必须确保你可以再次进入它。

你可以将这个部分放在一个方法中,并在默认情况下第一次调用这个方法,然后包括事件监听器、一个用于启动循环的特殊键和其他用于停止循环的键

类似的内容应涵盖所有情况:

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();

        }
    }
}

请详细说明无限while循环应该做什么。它在活动mq代理上推送消息。它必须停止和启动。它从哪里获取消息?是否可以创建一个可暂停的循环而不是可停止的循环。。例如你不会和你的女朋友分手,但你只是彼此休息一下,当你再次性欲时,你会恢复这段关系。。你知道我在说什么吗mean@letsjak我刚才读了…是的,我知道你的意思,但不,你不能暂停一个小时loop@letsjak你应该为我做贡献