在多线程程序中,我怀疑当一个线程在wait()时,它不会占用太多的cpu利用率,因此cpu可以交换来处理其他线程.@H_404_2@
例如,100个线程一起启动相同的任务,而50个线程实际执行任务,而其他50个线程等待直到所有50个任务完成.
后一种情况比前者花费的时间少得多.@H_404_2@
任何人都可以建议一些关于此的读物吗?@H_404_2@
最佳答案
wait方法有两个目的:@H_404_2@
>它将告诉当前正在执行的线程进入休眠状态(不使用任何cpu).
>它将释放锁定,以便其他线程可以唤醒并锁定.@H_404_2@
每当方法在同步块内部执行某些操作时,块中的任何内容都必须等待释放锁定的对象.@H_404_2@
@H_404_2@
synchronized (lockObject) {
// someone called notify() after taking the lock on
// lockObject or entered wait() so now it's my turn
while ( whatineedisnotready) {
wait(); // release the lock so others can enter their check
// now,if there are others waiting to run,they
// will have a chance at doing so.
}
}
必读:@H_404_2@