有 Java 编程相关的问题?

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

在while(true)循环中使用多线程wait()来模拟Java中的时钟

我试图用wait()和notify()在Java中模拟数字时钟。如果我运行以下代码(实际上是另一个非常简单的GUI类来显示时钟),我会得到一个非法的监视器异常。我是Java新手,所以我可能用错了wait()

public class JDigitalClock extends JLabel implements Runnable {

private static final long serialVersionUID = 1L;
private boolean stopped = false;
DateTimeFormatter dtf;
LocalDateTime now;

public JDigitalClock() {
    dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
    now = LocalDateTime.now();
    setText(dtf.format(now));
    setFont(new Font("Sans Serif", Font.PLAIN, 70));
    setHorizontalAlignment(SwingConstants.CENTER);
}

@Override
public void run() {
    while (true) {
        sleep();
        while (getStopped())
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        now = LocalDateTime.now();
        setText(dtf.format(now));
    }

}

public void setStopped(boolean stopped) {
    this.stopped = stopped;
    if (!stopped)
        notify();
}

public boolean getStopped() {
    return this.stopped;
}

public void sleep() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

共 (0) 个答案