CountDownLatch

使用的实例:

@Override
public <V> V get(Future<V> future) {
final CountDownLatch l = new CountDownLatch(1);
future.addListener(new FutureListener<V>() {
@Override
public void operationComplete(Future<V> future) throws Exception {
l.countDown();
}
});
try {
l.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// commented out due to blocking issues up to 200 ms per minute for each thread
// future.awaitUninterruptibly();
if (future.isSuccess()) {
return future.getNow();
}
throw convertException(future);
}

直接上代码

package com.hust.grid.leesf.cyclicbarrier;

import java.util.concurrent.CountDownLatch;

class MyThread extends Thread {
private CountDownLatch countDownLatch;

public MyThread(String name, CountDownLatch countDownLatch) {
super(name);
this.countDownLatch = countDownLatch;
}

public void run() {
System.out.println(Thread.currentThread().getName() + " doing something");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finish");
countDownLatch.countDown();
}
}

public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(2);
MyThread t1 = new MyThread("t1", countDownLatch);
MyThread t2 = new MyThread("t2", countDownLatch);
t1.start();
t2.start();
System.out.println("Waiting for t1 thread and t2 thread to finish");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " continue");
}
}

主线程main

CountDownLatch

这里aqs状态位为2,main线程被park。

t1执行后aqs状态位为1。

CountDownLatch

t2执行后aqs状态为。

CountDownLatch

main线程重获新生,清理掉aqs状态。

CountDownLatch

参考:

http://www.cnblogs.com/leesf456/p/5406191.html

上一篇:VIM 技巧 (一)全文统一添加


下一篇:解决 Oracle exp导出表数据时空表不能导出的问题