在操作系统中,线程有等待、就绪和运行这几种状态,等待队列中的线程是不会参与到CPU的竞争,只有就绪队列中的线程会参与到CPU的竞争,对应的在Java中的线程有6种状态:new、ready、running、waiting、timeWaiting和terminated这6中状态。
在Java的Thread类中有sleep方法,这个方法的调用会出让当前执行线程的CPU时间片持有当前线程持有的锁资源不释放,并且进入到等待队列中,待sleep时间到了,该线程才会进入到就绪队列参与到CPU时间片的竞争。sleep(0)是为了让当前线程让出CPU执行时间,让操作系统执行一次CPU调度,这个CPU调度会根据相应的CPU调度算法(优先级啥的)重新计算调度一个线程执行,sleep(0)当前线程不会进入到等待队列中,是进入到就绪队列中,也参与到CPU的竞争,所以有可能会立即拿到CPU时间片。
sleep(0)和yeild的区别:两者都是出让当前CPU,进入到就绪队列中,都有可能立即被分配到CPU时间片。
Thread.sleep在JVM中的实现
if (millis == 0) {
// When ConvertSleepToYield is on, this matches the classic VM implementation of
// JVM_Sleep. Critical for similar threading behaviour (Win32)
// It appears that in certain GUI contexts, it may be beneficial to do a short sleep
// for SOLARIS
if (ConvertSleepToYield) {
os::yield();
} else {
ThreadState old_state = thread->osthread()->get_state();
thread->osthread()->set_state(SLEEPING);
os::sleep(thread, MinSleepInterval, false);
thread->osthread()->set_state(old_state);
}
}
Thread.yeild在JVM中的实现:
if (ConvertYieldToSleep) {
os::sleep(thread, MinSleepInterval, false);
} else {
os::yield();
}
网友评论