import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
public class TestCountDownLatch {
private static List<String> mans = new ArrayList<String>();
private static CyclicBarrier barrier = null;
private static AtomicInteger costTimes = new AtomicInteger(0);
static {
mans.add("andy");
mans.add("jack");
mans.add("lili");
mans.add("alan");
mans.add("bill");
//barrier = new CyclicBarrier(mans.size() + 1);
}
public static class Walk implements Runnable {
private AtomicInteger ct = new AtomicInteger(0);
private String name;
private CountDownLatch latch;
public Walk(String name, AtomicInteger countTime, CountDownLatch cdl) {
ct = countTime;
this.name = name;
// latch = cdl;
}
@Override
public void run() {
int walkTime = new Random().nextInt(20);
try {
if ("lili".equals(name)) {
Thread.sleep(10000);
} else
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(name + " walk " + walkTime + "min");
// ct.addAndGet(walkTime);
// try {
// // barrier.await();
// latch.countDown();
// } catch (Exception e) {
//
// }
System.out.println(name + " walk over!");
System.out.println("all person walk " + ct.addAndGet(walkTime));
}
}
public static class Walk1 implements Callable<Integer> {
private String name;
public Walk1(String n) {
this.name = n;
}
@Override
public Integer call() {
int walkTime = new Random().nextInt(20);
try {
if ("lili".equals(name)) {
Thread.sleep(10000);
} else
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(name + " walk " + walkTime + "min");
return walkTime;
}
}
public static void main(String[] args) throws Exception {
// try {
// CountDownLatch latch = new CountDownLatch(mans.size());
// ExecutorService es = Executors.newFixedThreadPool(mans.size());
// for (String str : mans) {
// es.submit(new Walk(str, costTimes, latch));
// }
//
// es.shutdown();
// // latch.await();
// //barrier.await();
// System.out.println("TOTAL COST:" + costTimes + "min");
// } catch (Exception e) {
// System.out.println(e.getMessage());
// } finally {
//
// }
List<Future<Integer>> tasks = new ArrayList<Future<Integer>>();
ExecutorService es = Executors.newFixedThreadPool(mans.size());
for (String str : mans) {
Walk1 w = new Walk1(str);
FutureTask<Integer> f = new FutureTask<Integer>(w);
tasks.add(f);
es.submit(f);
}
es.shutdown();
Integer costTimes = 0;
for (Future<Integer> f : tasks) {
costTimes += f.get();
}
System.out.println("TOTAL COST:" + costTimes + "min");
}
}
计算几个人跑步总时间。。。