条件vs对象等待/通知 [英] Conditions vs objects wait/notify

查看:146
本文介绍了条件vs对象等待/通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于条件对象以及它们如何为每个对象提供多个等待集,并且区分哪个对象或一组对象/线程获得特定信号。 >
为什么不定期的 Object 这样做?例如。

I was reading about Condition objects and how they offer multiple wait-sets per object and also distinguishing which object or group of objects/threads get a specific signal.
Why doesn't a regular Object do that? E.g.

而不是:

final Condition notFull  = lock.newCondition();   
final Condition notEmpty = lock.newCondition();     

lock.lock();  
try {  
  while (count == items.length)  
     notFull.await();  
  items[putptr] = x;  
  if (++putptr == items.length) putptr = 0;  
      ++count;  
   notEmpty.signal();   

我们这样做:

final Object notFull  = new Object();     
final Object notEmpty = new Object();       

lock.lock();  
try {  
  while (count == items.length)  
     notFull.wait();  
  items[putptr] = x;  
  if (++putptr == items.length) putptr = 0;  
      ++count;  
   notEmpty.notify();   

难道我们还有多个等待集并区分被通知的线程吗?

Don't we still have multiple wait-sets and distinguish among notified threads?

推荐答案

在您的示例中,您在一个锁定上创建了2个条件。这是你不能做的内置同步 - 你不得不使用2对象来获得2个条件。

In your example you created 2 Conditions on one Lock. This is what you can't do with built-in synchronization - you had to use 2 Objects to get 2 conditions.

你的第二个代码被打破了,因为你没有锁在notFull和notEmpty但调用wait / notify - 你会得到IllegalMonitorStateException。但是如果你试图锁定它们,你会看到你不能同时做到。这是区别

And your second code is broken because you did not get lock on notFull and notEmpty but call wait / notify - you'll get IllegalMonitorStateException. But if you tried to lock them both you would see you cannot do that simultaneously. This is the difference

这篇关于条件vs对象等待/通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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