Thread.yeild方法详解

Thread.yeild方法详解,第1张

Thread.yeild方法详解

从原理上讲其实Thread.yeild方法其实只是给线程调度机制一个暗示:我的任务处理的差不多了,可以让给相同优先级的线程CPU资源了;不过确实只是一个暗示,没有任何机制保证它的建议将被采纳;

看一个例子就知道了;

public class LiftOff implements Runnable {

    protected int countDown = 5;

    private static int taskCount = 0;
private final int id = taskCount++; public LiftOff() { } public LiftOff(int countDown) {
this.countDown = countDown;
} public String status() {
// System.out.println(Thread.currentThread().getName());
return Thread.currentThread().getName() + "#" + id + "(" + (countDown > 0 ? countDown + ")" : "Liftoff!" + ")");
} @Override
public void run() {
// TODO Auto-generated method stub
/*
* --countDown:先减去,再赋值
* countDown--先赋值,再减去
*/
while (countDown-- > 0) {
System.out.println(status());
Thread.yield();// 让步【表示我的任务处理的差不多了,可以让步给其他线程资源了】;CPU资源给其他线程使用;t.join当前线程挂起,直到t线程调用结束后切回
/*
* try {
* TimeUnit.MILLISECONDS.sleep(100);
* } catch (InterruptedException e) {
* // TODO Auto-generated catch block
* // e.printStackTrace();
* System.err.println("异常终止...");
* }
*/ } }
public class ExecuteMethodPool {

    public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();// 无界队列:将为每个任务创建一个线程
// ExecutorService executorService = Executors.newFixedThreadPool(2);// 有限线程数队列
// ExecutorService executorService = Executors.newSingleThreadExecutor();// 有限线程数队列 for (int i = 0; i < 3; i++) { executorService.execute(new LiftOff());
}
executorService.shutdown(); } }

响应结果打印:

p.p1 { margin: 0; font: 12px Menlo }

pool-1-thread-2#1(4)

pool-1-thread-1#0(4)

pool-1-thread-3#2(4)

pool-1-thread-2#1(3)

pool-1-thread-3#2(3)

pool-1-thread-3#2(2)

pool-1-thread-1#0(3)

pool-1-thread-2#1(2)

pool-1-thread-3#2(1)

pool-1-thread-1#0(2)

pool-1-thread-2#1(1)

pool-1-thread-3#2(Liftoff!)

pool-1-thread-1#0(1)

pool-1-thread-2#1(Liftoff!)

pool-1-thread-1#0(Liftoff!)

以上标注的两个一样的线程先后执行 并没有遵守yeild给线程调度的建议

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/585807.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存