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

huangapple 未分类评论41阅读模式
英文:

wait() in a while (true) loop to simulate a Clock in Java

问题

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

Im trying to simulate a digital clock in Java by using wait() and notify(). If i run the following Code (well, actually a other very simlue GUI Class to display the Clock) i get a Illegal Monitor Exception. Im new to Java, so probably Ive used wait() the wrong way....

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

huangapple
  • 本文由 发表于 2020年4月10日 01:50:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/61127175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定