【问题标题】:Stop, close, end, thread in java based on condition根据条件停止,关闭,结束,java中的线程
【发布时间】:2018-06-06 18:17:41
【问题描述】:

我不知道如何让它工作。我希望这一步停止一次(startNumber == 0 || !Player.cCounting)!Player.cCounting 是一个被访问的boolean。如果满足任一条件,我希望循环停止。

public class Console {

    static long lastTime;
    static boolean cCounting = true;
    static long seconds = 0;
    static long delta = 0;
    static int startNumber = (int) Level.cookieTime / 1000;
    Thread countDown;

    public Console() {

        cookieCountDown();
        lastTime = System.currentTimeMillis();
    }

    public void cookieCountDown() {
        countDown = new Thread(new Runnable() {
            @Override
            public void run() {
                startNumber = (int) Level.cookieTime / 1000;
                while (startNumber != 0) {

                    cCounting = Game.enter;
                    //System.out.println(cCounting);
                    try {
                        Thread.sleep(0);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    while (startNumber > 0 && cCounting) {
                        long now = System.currentTimeMillis();
                        delta = now - lastTime;

                        if (delta >= 1000) {
                            delta = 0;
                            lastTime = System.currentTimeMillis();
                            System.out.println("cookie " + startNumber);// print countdown;
                            startNumber--;
                            System.out.println(Player.cCounting);
                            if (Player.cCounting = false) {
                                end();
                            }
                        }
                    }
                }
            }
        });
        countDown.start();
    }

    public void end() {
        System.out.println(startNumber);
        System.out.println(cCounting);
        if (startNumber == 0 || !Player.cCounting) {
            System.out.println("stop");
            //countDown.interrupt();
            //countDown.stop();
        }
    }
}

【问题讨论】:

    标签: java multithreading runnable


    【解决方案1】:

    你只需要退出你的循环。用return; 替换您的end(); 方法调用。并制作 startNumberPlayer.cCounting volatile 例如volatile static int startNumber

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多