线程中的yield()
屬于本地方法,放棄當(dāng)前的CPU資源,回到runnable狀態(tài)。
/*** A hint to the scheduler that the current thread is willing to yield* its current use of a processor. The scheduler is free to ignore this* hint.** <p> Yield is a heuristic attempt to improve relative progression* between threads that would otherwise over-utilise a CPU. Its use* should be combined with detailed profiling and benchmarking to* ensure that it actually has the desired effect.** <p> It is rarely appropriate to use this method. It may be useful* for debugging or testing purposes, where it may help to reproduce* bugs due to race conditions. It may also be useful when designing* concurrency control constructs such as the ones in the* {@link java.util.concurrent.locks} package.*/public static native void yield();Java線程中的Thread.yield( )方法,譯為線程讓步。顧名思義,就是說當(dāng)一個(gè)線程使用了這個(gè)方法之后,它就會(huì)把自己CPU執(zhí)行的時(shí)間讓掉,
讓自己或者其它的線程運(yùn)行,注意是讓自己或者其他線程運(yùn)行,并不是單純的讓給其他線程。
? ? ? ? yield()的作用是讓步。它能讓當(dāng)前線程由“運(yùn)行狀態(tài)”進(jìn)入到“就緒狀態(tài)”,從而讓其它具有相同優(yōu)先級(jí)的等待線程獲取執(zhí)行權(quán);但是,并不能保
證在當(dāng)前線程調(diào)用yield()之后,其它具有相同優(yōu)先級(jí)的線程就一定能獲得執(zhí)行權(quán);也有可能是當(dāng)前線程又進(jìn)入到“運(yùn)行狀態(tài)”繼續(xù)運(yùn)行!
? ? ? 舉個(gè)例子:一幫朋友在排隊(duì)上公交車,輪到Y(jié)ield的時(shí)候,他突然說:我不想先上去了,咱們大家來競(jìng)賽上公交車。然后所有人就一塊沖向公交車,
有可能是其他人先上車了,也有可能是Yield先上車了。
? ? ?但是線程是有優(yōu)先級(jí)的,優(yōu)先級(jí)越高的人,就一定能第一個(gè)上車嗎?這是不一定的,優(yōu)先級(jí)高的人僅僅只是第一個(gè)上車的概率大了一點(diǎn)而已,
最終第一個(gè)上車的,也有可能是優(yōu)先級(jí)最低的人。并且所謂的優(yōu)先級(jí)執(zhí)行,是在大量執(zhí)行次數(shù)中才能體現(xiàn)出來的。
?
轉(zhuǎn)載于:https://www.cnblogs.com/DDiamondd/p/11290942.html
總結(jié)
以上是生活随笔為你收集整理的线程中的yield()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。