根据条件在java中停止,关闭,结束,线程

时间:2018-06-06 18:17:42

标签: java multithreading runnable

我不知道如何让这个工作。我想让这个踏板停一次(startNumber == 0 || !Player.cCounting)!Player.cCountingboolean,可以访问。如果满足任一条件,我希望循环停止。

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

1 个答案:

答案 0 :(得分:0)

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