Skip to content

Instantly share code, notes, and snippets.

@searover
Created July 8, 2020 20:33
Show Gist options
  • Save searover/748c49c22a8e2729a82e18a20939bd78 to your computer and use it in GitHub Desktop.
Save searover/748c49c22a8e2729a82e18a20939bd78 to your computer and use it in GitHub Desktop.
class GuardedObject<T> {
// 受保护的对象
T obj;
final Lock lock = new ReentrantLock();
final Condition done = lock.newCondition();
final int timeout = 1;
T get(Predicate<T> p) {
lock.lock();
try{
// MESA管程推荐写法
while(!p.test(obj)){
done.await(timeout, TimeUnit.SECONDS);
}
}finally{
lock.unlock();
}
return obj;
}
void onChange(T obj){
lock.lock();
try{
this.obj = obj;
done.signalAll();
}finally{
lock.unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment