如何用notify和notifyall解决饥饿问题? [英] How to solve starvation with notify and notifyall?

查看:140
本文介绍了如何用notify和notifyall解决饥饿问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用notifynotifyall解决饥饿问题?

How to solve starvation with notify and notifyall?

如果我们有4个线程,则等待获取对同一obj的锁,并且当前线程调用notify()

If we have 4 threads, waiting to acquire a lock on same obj,and the current thread calls notify()

JVM将选择任何一个线程.调用notify()的线程是否有可能再次被JVM选中,就像调用notify()之后的线程一样,它也在等待线程列表中.

The JVM will select any one thread. Is it possible that thread which called notify(), can again be picked by JVM, as after calling notify(), it would be also in waiting thread list.

如果其中一个线程的调用次数比其他线程更多,这可能会导致饥饿问题,除非有某种机制会首先选择等待时间最长的线程.

This might lead to starvation problem if one of the thread is invoked more number of times than others, unless there is some mechanism where longest waiting thread is picked up first.

我在这里假设所有线程都具有相同的优先级.如果线程优先级不同,我认为在notify()

I am assuming here that all threads are of same priority. If thread priorities are different, I think highest priority thread will be picked up when notify()

此外,notifyall()也会出现相同的问题,我认为我们不知道将选择哪个线程.

Also, same issues would crop up with notifyall() I think where we don't know which thread will be picked.

推荐答案

如果您关心哪个线程得到通知,则说明您做错了什么.无论需要执行什么通知,任何等待通知 的线程都可以执行此操作.如果此逻辑不适用于您的用例,则notify不适合您的用例.

If you care which thread gets notified, you are doing something wrong. Whatever the notification requires to be done, any thread that is waiting for a notification must be able to do it. If this logic doesn't apply to your use case, then notify is not appropriate for your use case.

对线程公平性的担忧通常表示设计不良的代码.确保您的代码仅能真正执行您想要的工作,并且在必要时首先执行最重要的工作是您的工作.您不应该期望调度程序以某种方式执行此操作.调度程序的工作是尽可能多地完成工作,以增强流程之间的优先级和公平性.程序员的工作是编写能正常工作的代码.

Concern about thread fairness generally indicates poorly-designed code. It's your job to make sure your code only does work you actually want it to do and, if necessary, does the most important work first. You shouldn't be expecting the scheduler to somehow do this. The scheduler's job is to get as much work done as possible, enforcing priorities and fairness between processes. The programmer's job is to write code that does the right work.

这篇关于如何用notify和notifyall解决饥饿问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆