如何停止和重新启动线程内的循环? [英] How to stop and restart a loop inside a thread?

查看:52
本文介绍了如何停止和重新启动线程内的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swing 使用 Java.我正在开发绘图应用程序.只要布尔变量设置为true,它就有一个不断运行的恒定更新循环.循环位于线程内部.

I'm working with Java using Swing. I am working on a drawing application. It has a constant update loop that runs constantly, as long as a Boolean variable is set to true. The loop is located inside a thread.

它工作正常,但现在我希望循环仅在特定时间运行(仅在按下鼠标时),否则不运行.(因此不会白白浪费内存).

It works fine, but now I want the loop to only run at certain times (only when the mouse is pressed), and otherwise not run. (Thus not wasting memory for nothing).

要停止循环,我可以简单地将该变量设置为 false,这样 while 循环就会退出.但我的问题是,如何在停止循环后重新启动循环?将该变量设置回 true 不会重新启动循环,因为程序已经在该循环之外(我说得对吗?).如果是这样,这样做的好方法是什么?

To stop the loop, I can simply set that variable to false, so the while loop will exit. But my question is, how can I restart the loop after stopping it? Setting that variable back to true will not restart the loop, because the program is already outside of that loop (am I correct?). If so, what would be a good way to do this?

我的循环:

public void run(){

    int TICKS_PER_SECOND = 50;
    int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    int MAX_FRAMESKIP = 10;

    long next_game_tick = System.currentTimeMillis();
    int loops;

    boolean app_is_running = true;

    while( app_is_running ) {

        loops = 0;
        while( System.currentTimeMillis() > next_game_tick && loops < MAX_FRAMESKIP) {

            update();
            catch (AWTException e) { e.printStackTrace(); }

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        repaint();
    }

}

推荐答案

将循环移动到它自己的方法.然后,当您需要停止时,您可以从该方法返回.当您想返回时,只需再次调用该方法即可.

Move your loop to it's own method. Then when you need to stop you can return from the method. When you want to go back in just call the method again.

这篇关于如何停止和重新启动线程内的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆