关于Object.wait(long t)的问题,请指教
下面的代码照理应该输出1000左右的数字,但是输出的是64.
我是这样想的:
首先Object.wait(long t)是很精确的,Timer类也是用该
方法来实现执行时间的安排的。
然后看run函数,在stop前做一个无限循环,而且获得本身
的管程,所以每次执行wait(1)这条语句都会停留1微秒,
然后作cnt的加操作,所以经过1000毫秒的sleep应该加到
1000才对呀,请问大家我想的错在哪里?
public class Test implements Runnable {
boolean flag = true;
int cnt = 0;
public void run() {
System.out.println("start");
synchronized(this) {
while(flag) {
try {
wait(1);
cnt++;
}catch(Exception e){}
}
}
}
void stop() {
flag = false;
System.out.println("cnt="+cnt);
}
public static void main(String[] args) throws Exception {
Test t = new Test();
Thread thread = new Thread(t);
thread.start();
Thread.sleep(1000);
t.stop();
}
}