条件vs等待通知机制 [英] Condition vs wait notify mechanism

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

问题描述

使用Condition接口/实现比传统的等待通知机制有什么优点?这里我引用Doug Lea写的意见: -


条件因素将对象监视器方法(wait,notify和notifyAll)转换为不同的对象,以通过使用任意Lock实现来组合每个对象具有多个等待集的效果。当一个Lock替换了同步方法和语句的使用时,条件将替换对象监视方法的使用。


我看到这是一种更为面向对象的实现等待/通知机制的方法。但是有没有比前者更好的优势?

解决方案

有很多优点重要的如下:



条件接口附带两个额外方法


$ b

1)boolean awaitUntil(Date deadline)throws InterruptedException:
使当前线程等待,直到发出信号或中断,或指定的截止时间已过。



2)awaitUninterruptibly():
使当前线程等待,直到发出信号。



如果当前线程进入此方法时设置了当前线程的中断状态,或者在等待期间线程中断,它将继续等待,直到发出信号。当它最终从这个方法返回时,它的中断状态仍然被设置。



上述两种方法在默认监视器中不存在于对象类中,在某些情况下,我们要设置线程的等待时间,我们可以在条件接口。



在某些情况下,我们不希望线程被中断,并希望当前线程等待,直到它被信号,然后我们可以去awaitUninterruptibly方法存在





< /docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html#awaitUntil%28java.util.Date%29rel =nofollow> http:// docs .oracle.com / javase / 1.5.0 / docs / api / java / util / concurrent / locks / Condition.html#awaitUntil%28java.util.Date%29


What is the advantage of using Condition interface/implementations over the conventional wait notify mechanism ?Here i quote the comments written by Doug Lea :-

Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

I see this is a more Object Oriented way of implementing wait/notify mechanism. But is there a sound advantage over the former ?

解决方案

There are many advantages like mentioned above about Condition Interface some important are as follows:

Condition interface comes with Two extra methods that are:

1)boolean awaitUntil(Date deadline)throws InterruptedException : Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.

2)awaitUninterruptibly() : Causes the current thread to wait until it is signalled.

If the current thread's interrupted status is set when it enters this method, or it is interrupted while waiting, it will continue to wait until signalled. When it finally returns from this method its interrupted status will still be set.

The above two methods are not present in default monitor that is in object class,in some situations we want to set the deadline for thread to wait then we are able to do that by Condition interface.

In some situations we don't want thread to be interrupted and want current thread to wait until it is signaled then we can go for awaitUninterruptibly method present in Condition Interface.

For more information Condition Interface Java Documentation:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html#awaitUntil%28java.util.Date%29

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

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