notify() 和 signal() 唤醒线程是随机的吗?

本文探讨了Java中`synchronized`和`ReentrantLock`的`notify()`及`signal()`方法在唤醒线程时的公平性问题。实验结果显示,无论是`notify()`还是`signal()`,在特定环境下都表现出公平性,即线程按照先进先出的顺序被唤醒。实验在JVM环境下进行,揭示了这些方法的内部实现可能考虑了公平性策略。
摘要由CSDN通过智能技术生成
一、概述

synchronized 是非公平锁。ReentrantLock 默认是非公平锁,但可设置为公平锁

那线程通过Object.nofity()Condition.signal() 被唤醒时是否是公平的呢?

先说结果,在Java 1.8 HotSpot下,两者都是公平的。

查看Java文档:

void signal()

Wakes up one waiting thread.
If any threads are waiting on this condition then one is selected for waking up. That thread must then re-acquire the lock before returning from await.

Implementation Considerations

An implementation may (and typically does) require that the current thread hold the lock associated with this Condition when this method is called. Implementations must document this precondition and any actions taken if the lock is not held. Typically, an exception such as IllegalMonitorStateException will be thrown.
public final void notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.

Object.nofity() 的文档明确说一个随机的线程将被唤醒,但具体情况将由实现者决定,因为Object.nofity()是一个native方法。

Condition.signal() 的文档则说一个被选定的线程将被唤醒。

二、实验
2.1 对notify()方法进行实验:
public class NotifyTest {
   

    private final Object object = new Object();
    private List<Integer> sleepList = new LinkedList<>
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值