英文:
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();
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论