线程的礼让可以通过 Thread.yield() 实现,可以控制优先级低的线程礼让,以便增加优先级高的线程获得优先执行的几率。
具体示例代码如下所示:
package com.fanfengping.demo; import lombok.extern.slf4j.Slf4j; /** * 线程礼让:通过 Thread.Yield() 实现 */ @Slf4j public class Demo13RunnableYield implements Runnable { @Override public void run() { String threadName = Thread.currentThread().getName(); for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (i % 2 == 0 && "A".equals(threadName)) { System.out.print(threadName + " 线程礼让,"); Thread.currentThread().yield(); } if (i % 3 == 0 && "B".equals(threadName)) { System.out.print(threadName + " 线程礼让,"); Thread.currentThread().yield(); } if (i % 4 == 0 && "C".equals(threadName)) { System.out.print(threadName + " 线程礼让,"); Thread.currentThread().yield(); } System.out.println(threadName + " 执行," + i); } } public static void main(String[] args) { Demo13RunnableYield demo13RunnableYield = new Demo13RunnableYield(); Thread threadYieldA = new Thread(demo13RunnableYield, "A"); Thread threadYieldB = new Thread(demo13RunnableYield, "B"); Thread threadYieldC = new Thread(demo13RunnableYield, "C"); threadYieldC.setPriority(Thread.MAX_PRIORITY); threadYieldA.start(); threadYieldB.start(); threadYieldC.start(); } }
执行后,控制台输出如下所示:
C 线程礼让,B 线程礼让,A 线程礼让,B 执行,0
C 执行,0
A 执行,0
B 执行,1
C 执行,1
A 执行,1
C 执行,2
A 线程礼让,B 执行,2
A 执行,2
B 线程礼让,C 执行,3
A 执行,3
B 执行,3
C 线程礼让,B 执行,4
A 线程礼让,C 执行,4
A 执行,4
A 执行,5
C 执行,5
B 执行,5
A 线程礼让,B 线程礼让,C 执行,6
B 执行,6
A 执行,6
B 执行,7
A 执行,7
C 执行,7
A 线程礼让,C 线程礼让,B 执行,8
C 执行,8
A 执行,8
B 线程礼让,B 执行,9
A 执行,9
C 执行,9
Process finished with exit code 0
从程序的运行结果,可以看出:
1、优先级高的线程获得优先执行的几率较大,但并非完全优先执行,取决于 CPU 的调度分配;
2、线程礼让并非完全的礼让,礼让后仍可能优先执行;