【发布时间】:2015-11-13 12:39:29
【问题描述】:
所以我做了一个程序,所以在运行程序时会出现一个时钟。所以。当我按下“开始”按钮时,时钟应该在一个范围内随机运行并作为时钟运行(我的意思是像数字,15:18:19、15:18:20)。但我现在的问题是每当我按下程序时。时钟保持在同一位置,并且当将睡眠时间更改为 500 等时。然后它开始移动,但时间似乎要快得多(因为它应该睡眠 1000)。但是我没有在代码中看到它应该去的问题。但是也许你们中的一些人可以帮助我。
public void startClock() {
Thread t2 = new Thread() {
public void run() {
if (clocking) {
Random rand = new Random();
while(clocking){
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
movingClock.setText(hour + ":" + minute + ":" + second);
int x = rand.nextInt(100) + 1;
int y = rand.nextInt(100) + 1;
movingClock.setBounds(x, y, 150, 150);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t2.start();
}
其中时钟 = true。因为每当我按下按钮。我将时钟设置为 true,然后运行 startClock()。
但正如我之前所说。只有当我将睡眠时间更改为低于 500 时,数字时钟才会随机运行。如果它是 sleep(1000),我该如何让它工作?
编辑新的:
public void startMoving() {
Thread t1 = new Thread() {
public void run() {
if (moving) {
Random random = new Random();
while (moving) {
int x = random.nextInt(100) + 1;
int y = random.nextInt(100) + 1;
movingDisplay.setBounds(x, y, 150, 150);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
}
public void startClock() {
Thread t2 = new Thread() {
public void run() {
if (clocking) {
Random rand = new Random();
while(clocking){
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
movingClock.setText(hour + ":" + minute + ":" + second);
int x = rand.nextInt(100) + 1;
int y = rand.nextInt(100) + 1;
movingClock.setBounds(x, y, 150, 150);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
movingClock.setText(hour + ":" + minute + ":" + second);
movingClock.setBounds(x, y, 150, 150);
movingDisplay.setBounds(x, y, 150, 150);
}
} );
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t2.start();
}
【问题讨论】:
-
我看不出有什么问题,您是否尝试过使用 2 Thread.sleep(500);而不仅仅是 thread.sleep(1000);
-
试着给你的随机种子。新随机(System.currentTimeMillis());
-
在制作时钟并每 1000 毫秒刷新一次时要小心。如果你在 14:10:10.999 得到时间,然后你执行一些计算然后显示一些东西,你会花费几毫秒,然后你休眠 1000 毫秒然后执行一些操作,当你下次得到时间时它可能是 14 :10:12.005,你永远不会在屏幕上显示 14:10:11。
-
@Paul 我还没有尝试过,会在第二个@newbieee 嗯,它唯一的 `Random rand = new Random(); @StephaneM 哦,好吧!它应该只需要当前时间。但迟到或早到一秒钟并不重要:)
-
所以我尝试了线程睡眠 500 和没有结果的随机函数
标签: java multithreading calendar jframe jpanel