有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java更新runnable类中的变量值

我是java的初学者。我无法从主类更新TimerRunnable类中的变量。这可能吗

这是我的主要任务。爪哇

class Main {
    public static void main(String[] args) {
        TimerRunnable tr = new TimerRunnable(5);
        Thread thread = new Thread(tr);

        thread.start();

        try {
            Thread.sleep(2000L);
        } catch(Exception ignored) {}

        System.out.println("main");
        tr.resetTimer(true);
    }
}

时光流逝。爪哇:

import java.lang.Thread;

public class TimerRunnable implements Runnable {
    public boolean reset = false;
    private int sec;

    public TimerRunnable(int sec) {
        this.sec = sec;
    }

    public synchronized void resetTimer(boolean v) {
        this.reset = v;
    }

    private synchronized boolean checkResetTimer() {
        return this.reset;
    }

    @Override
    public void run() {
        int i = this.sec;

        while(i>=0) {
            if(this.checkResetTimer()) {
                i=sec;
                System.out.println(i);
            }

            System.out.println(Thread.currentThread().getName() + " = " + i + "/" + sec);
            try {
                Thread.currentThread().sleep(1000L);
            } catch(Exception e) {}

            if(this.checkResetTimer()) {
                resetTimer(false);
            }

            i--;
        }
    }
}

输出:

[me@laptop java]$ java Main
Thread-0 = 5/5
Thread-0 = 4/5
main
Thread-0 = 3/5
Thread-0 = 2/5
Thread-0 = 1/5
Thread-0 = 0/5

预期产出:

[me@laptop java]$ java Main
Thread-0 = 5/5
Thread-0 = 4/5
main
Thread-0 = 5/5
Thread-0 = 4/5
Thread-0 = 3/5
Thread-0 = 2/5
Thread-0 = 1/5
Thread-0 = 0/5

我更新TimerRunnable类中的变量的目标是使倒计时计时器可以返回到其原始值


共 (0) 个答案