有没有一种方法可以使对象只能由访问特定方法的第一个线程使用? [英] Is there a way to make an object usable only by the first thread that accesses a specific method?

查看:64
本文介绍了有没有一种方法可以使对象只能由访问特定方法的第一个线程使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以由任何线程创建的对象,但是在线程调用myObject.use()的那一刻,该对象只能被该线程使用,直到调用myObject.release()为止.

I want an object that can be created by any thread, but the moment a thread calls myObject.use() it can only be used by that thread until myObject.release() is called.

我不想强迫开发人员将该对象/类的所有方法调用包装在同步块中(我知道可以将其用于近似此功能),因为如果他们忘记将所有从myObject.use()myObject.release()的调用都包装在同一个同步块中.

I don't want to force the developers to have to wrap all method calls for this object/class in synchronized blocks (which I know could be used to approximate this functionality) as that's likely to lead to misuse of the object if they forget to wrap all calls from myObject.use() to myObject.release() in the same synchronized block.

这可能吗?

是否可以使用 ReentrantLock ?

Could it be done with a ReentrantLock?

推荐答案

可以做到. use()方法应该同步,因此一次只能由一个线程调用,并将调用线程作为锁定线程存储在私有volatile变量中.所有调用-包括use()-应该首先检查是否存在存储的锁定线程,然后立即返回-如果您愿意,则抛出异常-如果存在这样的线程并且它与调用线程不匹配. release()也应该同步,并且可以删除存储的锁定线程,从而允许下一次调用use()来存储新的锁定线程.

Sure it can be done. The use() method should be synchronized, so it can be called by only one thread at a time, and store the calling thread as the locking thread in a private volatile variable. All calls - including use() - should first check if there is a stored locking thread and immediately return - or throw an exception if you prefer - if there is such a thread and it doesn't match the calling thread. release() should also be synchronized and can remove the stored locking thread, allowing the next call to use() to store a new locking thread.

这篇关于有没有一种方法可以使对象只能由访问特定方法的第一个线程使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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