启动和停止无限循环

Posted

技术标签:

【中文标题】启动和停止无限循环【英文标题】:Start and stop an infinite while loop 【发布时间】:2014-11-04 09:52:17 【问题描述】:

我正在尝试找到一种解决方案来启动和停止控制台中的无限 while 循环。

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

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

【问题讨论】:

请详细说明你的无限while循环应该做什么。 它将消息推送到活动的 mq 代理上。它必须停止和启动。 它从哪里得到消息? 【参考方案1】:

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

【讨论】:

是否有可能制作一个可暂停的循环而不是一个可停止的循环.. 例如......你不会和你的 gf 分手,但你只是休息一下,当你角质时你又恢复了关系..你知道我的意思 @letsjak WTF 我刚刚读过...是的,我知道你的意思,但不,你不能暂停循环 @letsjak 你应该贡献给area51.stackexchange.com/proposals/77052/relationships【参考方案2】:

这样的东西应该涵盖所有情况:

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】:

你可以把这部分放在一个方法中,第一次默认调用这个方法,然后包含事件监听器,一个特定的启动键和停止循环的其他键。

【讨论】:

以上是关于启动和停止无限循环的主要内容,如果未能解决你的问题,请参考以下文章

Objective C如何在从第一个VC移动到第二个时停止无限循环

如何在useEffect中停止无限循环?

Python - 用于停止无限循环的键盘命令? [重复]

当没有更多数据时如何停止无限循环(分页)

Flutter 在无限循环中发送 http 请求

如何在useeffect钩子中停止无限循环