定时输出某一数据的问题

weixin_40835965 2018-07-04 03:56:16
package com.demo;
import java.util.*;
public class test {
public static void main(String[] args) {
long time = System.currentTimeMillis();
while(true) {
if((System.currentTimeMillis()-time)%1000 == 0)
System.out.println(new Date(System.currentTimeMillis()));
}
}
}

上面是我的代码,我想每个一秒输出一下当前时间,运行后输出的结果为什么会有重复的?
就像这样:
Wed Jul 04 15:51:14 CST 2018
Wed Jul 04 15:51:14 CST 2018
Wed Jul 04 15:51:14 CST 2018
Wed Jul 04 15:51:14 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
Wed Jul 04 15:51:15 CST 2018
...全文
130 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_32427077 2018-07-30
  • 打赏
  • 举报
回复
线程休息一秒
weixin_41378799 2018-07-05
  • 打赏
  • 举报
回复
在每个1ms内, CPU执行了多次多次:

if((System.currentTimeMillis()-time)%1000 == 0)
System.out.println(new Date(System.currentTimeMillis()));

所以在那个1ms内, System.currentTimeMillis()返回的值都相同,因此输出多次。
verejava 2018-07-04
  • 打赏
  • 举报
回复
Java 常用类库 之 Timer TimerTask

http://www.verejava.com/?id=17159702655333
天行归来 2018-07-04
  • 打赏
  • 举报
回复

public static void main(String[] args) {
long lasttick = System.currentTimeMillis();
while(true) {
if((System.currentTimeMillis()-lasttick)>=1000){
lasttick = System.currentTimeMillis();
System.out.println(new Date(System.currentTimeMillis()));
}
}
}
pzx521521 2018-07-04
  • 打赏
  • 举报
回复
因为在1MS里已经执行完了 加个 sleep 就好了把

58,452

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧