如果在同步方法中调用 thread.yield() 是否会失去对对象的锁定?

Does thread.yield() lose the lock on object if called inside a synchronized method?(如果在同步方法中调用 thread.yield() 是否会失去对对象的锁定?)

本文介绍了如果在同步方法中调用 thread.yield() 是否会失去对对象的锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 Thread.currentThread().yield() 是对线程调度程序的通知,它可以将 cpu 周期分配给具有相同优先级的其他线程(如果存在).我的问题是:如果当前线程已锁定某个对象并调用 yield(),它会立即失去该锁定吗?而当线程调度器发现没有这样的线程来分配cpu周期时,调用yield()的线程将再次争夺锁定它之前丢失的对象??

I understand that Thread.currentThread().yield() is a notification to thread scheduler that it may assign cpu cycle to some other thread of same priority if any such is present. My question is: If current thread has got lock on some object and calls yield(), will it loses that lock right away? And when thread scheduler finds out there is no such thread to assign cpu cycle, then the thread which has called yield() will again be in fight to get lock on the object which it has lost earlier??

我在 javadoc 和论坛中找不到它 [http://www.coderanch.com/t/226223/java-programmer-SCJP/certification/does-sleep-yield-release-lock] 有 50-50答案.

I couldn't find it in javadoc and forums [http://www.coderanch.com/t/226223/java-programmer-SCJP/certification/does-sleep-yield-release-lock] have 50-50 answers.

我认为yield()(比如说thread1)应该释放锁,因为如果某个相同优先级的线程(比如说thread2)想要对同一个对象进行操作,那么线程调度程序就有机会最终将 cup 分配给 thread2.

I think yield() (lets say thread1) should release lock because if some thread (lets say thread2) of same priority wants to operate on same object, then it can have chance when thread scheduler eventually assign cup to thread2.

推荐答案

没有.Thread.yield() 不像 Object.wait().它只是放弃控制以允许线程切换.它不会影响您程序的并发性.

No. Thread.yield() is not like Object.wait(). It just gives up control to allow a thread switch. It will have no effect on the concurrency of your program.

无法保证调度程序在产生后将运行哪个线程.

There is no guarantee which thread the scheduler will run after a yield.

这篇关于如果在同步方法中调用 thread.yield() 是否会失去对对象的锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果在同步方法中调用 thread.yield() 是否会失去对对象的锁定?

基础教程推荐