Created
July 8, 2020 20:33
-
-
Save searover/748c49c22a8e2729a82e18a20939bd78 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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