日期:2014-05-18  浏览次数:20634 次

java while循环的时间逻辑判断
光棍节来了 又去天猫抢红包。http://1111.tmall.com/?ali_trackid=2:mm_33231665_4172057_14416052:1383558704_3k6_1416935566&upsid=01c0c1ad31cb10952108e34c7deb3009&clk1=01c0c1ad31cb10952108e34c7deb3009
规则很简单就是8秒钟之内不断点击鼠标。
写了段测试代码如下:
public class Test implements Runnable {
Go go;
private String currentTime;
private Date now = new Date();
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");

public void run() {
go = new Go();
/**
 * 8s=10ms*800 我让它休眠10ms,再给count+1,
 * 忽略调用函数和count++的时间也就是说当count==800时就刚好运行了8秒
 */
int count = 0;
while (true && count < 850) {
try {
go.go_R(653, 546);// 模拟鼠标点击函数
Thread.sleep(10);
count++;

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public static void main(String[] args) {
Thread t = new Thread(new Test());
t.start();
}

}


在测试过程中问题来了,为什么每次运行4.5秒左右程序就结束了?是我的逻辑有问题?还是哪里写错了
java while循环 控制时间

------解决方案--------------------
go.go_R(653, 546);// 模拟鼠标点击函数
这个操作也需要时间的吧?
你可以把这个换成打印语句试下
------解决方案--------------------
原来用openGL的时候遇见过,按键盘会加快动画运行速度的。按鼠标应该会对程序造成一个interrupt,可能会影响这个计时系统吧。
 while (true && count < 850) {
            try {
              long start = System.currentTimeMillis();
              go.go_R(653, 546);// 模拟鼠标点击函
                Thread.sleep(10);
                count++;
                long end = System.currentTimeMillis();
                System.out.println(end - start);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

看看每次是不是都是 10ms