Java 多线程 yield方法
理論上,yield意味著放手,放棄,投降。一個調用yield()方法的線程告訴虛擬機它樂意讓其他線程占用自己的位置。這表明該線程沒有在做一些緊急的事情。注意,這僅是一個暗示,并不能保證不會產生任何影響。
在Thread.java中yield()定義如下:
| 1 2 3 4 5 6 7 | /** ??* 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. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU. ??* Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect. ??*/ public static native void yield(); |
讓我們列舉一下關于以上定義重要的幾點:
- Yield是一個靜態的原生(native)方法
- Yield告訴當前正在執行的線程把運行機會交給線程池中擁有相同優先級的線程。
- Yield不能保證使得當前正在運行的線程迅速轉換到可運行的狀態
- 它僅能使一個線程從運行狀態轉到可運行狀態,而不是等待或阻塞狀態
package java_thread.learn01.c002;
public class yieldTest extends Thread{
?? ?@Override
?? ?public void run(){
?? ??? ?long btime = System.currentTimeMillis();
?? ??? ?int count = 0;
?? ??? ?for(int i = 0;i<50000000;i++){
?? ??? ??? ?Thread.yield();
?? ??? ??? ?count = count + (i + 1);
?? ??? ?}
?? ??? ?long etime = System.currentTimeMillis();
?? ??? ?System.out.println("用時:" +(etime -btime) + "毫秒");?? ?
?? ?}
}
package java_thread.learn01.c002;
public class yieldRun {
?? ?public static void main(String[] args) {
?? ??? ?yieldTest yt = new yieldTest();
?? ??? ?yt.start();
?? ?}
}
上面代碼,如果注釋Thread.yield();,則時間20毫秒左右,如果不注釋,則5030毫秒左右,自己測試看看。
總結
以上是生活随笔為你收集整理的Java 多线程 yield方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java线程暂停与恢复suspend和r
- 下一篇: Java多线程之优先级setPriori