您的位置:首页 > 编程语言 > Java开发

java多线程组件一:CountDownLatch使用方法的总结

2012-07-12 22:11 856 查看
根据从资料上以及习题时间的总结CountDownLatch 做的事情就是通过对一个计数器的控制,来保证一批动作的执行,且同步性保证个这个计数器的值在多线程之间共享的有效性.

下面有个简单的例子可以说明这点:

public class CountDownLatchDemo {
public static void main(String[] args) {
/*
* CountDownLatch's parameter will decide whether to print waiting
* information
* if parameter >10 will never can't to execute finished information
* if parameter==0 , don't need to waiting call working()
*/
//in think in java construct parameter is 100, will lead to never print waiting finished information
CountDownLatch latch = new CountDownLatch(10);
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
es.execute(new WaitingTask(latch));
}
for (int i = 0; i < 10; i++) {
es.execute(new WokingTask(latch));
}
es.shutdown();
System.out.println("Existing");
}
}

class WokingTask implements Runnable {
private static int	         count	= 0;
private int	                 id	   = count++;
private final CountDownLatch	latch;

public WokingTask(CountDownLatch latch) {
this.latch = latch;

}

public String toString() {
return "working:" + id;
}

public void run() {
try {
working();
latch.countDown();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public void working() {
System.out.println(this + "working");
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

class WaitingTask implements Runnable {
private static int	         count	= 0;
private int	                 id	   = count++;
private final CountDownLatch	latch;

public WaitingTask(CountDownLatch latch) {
this.latch = latch;
}

public String toString() {
return "waiting:" + id;
}

public void run() {
try {
latch.await();
System.out.println(this + " waiting finished....");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息