我正在尝试创建一个简单的小程序,它只会计算秒数。 出于某种原因,我的代码从“2”开始并以偶数计数。 仔细查看我的代码后,我看不出为什么会这样做!有人可以帮帮我吗?
import java.applet.Applet;
import java.awt.Graphics;
public class Main extends Applet implements Runnable {
int seconds= 0;
public void init() {
setSize(50, 50);
Thread thread = new Thread(this);
thread.start();
Thread timer = new Thread(this);
timer.start();
}
public void run() {
while (true) {
try {
System.out.println(String.valueOf(seconds));
seconds= seconds +1;
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g){
g.drawString(String.valueOf(seconds), 25, 25);
}
}
答案 0 :(得分:2)
首先,您启动了两个线程,在相同的持续时间内递增相同的变量。这就是它重复两次的原因。
其次,不是在线程休眠后递增,而是最好使用它:
long start = System.currentTimeMillis();
while(true){
try {
System.out.println(String.valueOf(seconds));
seconds= (System.currentTimeMillis()-start)/1000;
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
答案 1 :(得分:0)
我会改变一些事情。首先,你应该扩展JApplet
。您只需要一个Thread
,应该存储startTime并计算秒数,您应该在刷新之间清除绘图区域。当我这样改变时,它可以在这里工作 -
public class Main extends JApplet implements ActionListener {
private long startTime = 0;
final int width = 100;
final int height = 100;
public void init() {
setSize(width, height);
startTime = System.currentTimeMillis();
Timer t = new Timer(1000, this);
t.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
long seconds = (System.currentTimeMillis() - startTime) / 1000l;
g.clearRect(0, 0, width, height);
g.drawString(String.valueOf(seconds), 25, 25);
}
@Override
public void actionPerformed(ActionEvent e) {
long seconds = (System.currentTimeMillis() - startTime) / 1000l;
System.out.println(seconds);
repaint();
}
}