package cn.uto.oo.tt;
import java.util.concurrent.CountDownLatch;
public class LatchVal<T> {
private T v=null;
private final CountDownLatch c=new CountDownLatch(1);
public synchronized void setVal(T val){
if(c.getCount()>0){
v=val;
c.countDown();
}
}
public T getVal() throws InterruptedException{
c.await();
synchronized (this) {
return v;
}
}
public static void main(String[] args) throws InterruptedException {
final LatchVal l=new LatchVal<String>();
new Thread(new Runnable() {
public void run() {
l.setVal("OK");
}
}).start();
System.out.println(Thread.currentThread().getName()+" "+l.getVal());
}
}
CountDownLatch 实现可以保存值的闭锁
最新推荐文章于 2025-03-07 18:14:27 发布