随手记两个线程同步结束的例子
1.用Callable<V>
2.用CountDownLatch(CyclicBarrier也可以达成一样的效果,写法大同小异)
1.用Callable<V>
public class CallableThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
DateTime dt1 = DateTime.now();
String name = Thread.currentThread().getName();
System.out.println(name + " start on " + dt1) ;
Thread.sleep(new Random().nextInt(10) * 1000);
DateTime dt2 = DateTime.now();
Integer cost = (int) ((dt2.getMillis() - dt1.getMillis()) / 1000);
System.out.println(name + " end on " + dt2 + " cost time : " + cost);
return cost;
}
public static void main(String[] args) {
List<Future<Integer>> count = Lists.newArrayList();
ExecutorCompletionService<Integer> service = new ExecutorCompletionService<Integer>(Executors.newFixedThreadPool(5));
for(int i=0; i< 5; i++) {
count.add(service.submit(new CallableThread()));
}
Integer total = 0;
try {
for(int i=0; i<count.size(); i++) {
Future<Integer> f;
f = service.take();
total += f.get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("total cost:" + total + " aver cost " + total/count.size());
}
}
2.用CountDownLatch(CyclicBarrier也可以达成一样的效果,写法大同小异)
public class CountDownLatchDemo implements Runnable {
CountDownLatch latch;
static final Map<String,Long> count = Maps.newConcurrentMap();
ThreadDemo(CountDownLatch latch ){
this.latch = latch;
}
public void run() {
DateTime dt1 = DateTime.now();
String name = Thread.currentThread().getName();
System.out.println(name + " start on " + dt1);
try {
Thread.sleep(new Random().nextInt(10) * 1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
DateTime dt2 = DateTime.now();
Long cost = dt2.getMillis() - dt1.getMillis();
System.out.println(name + " end on " + dt2 + " cost time : " + cost);
count.put(name, cost);
latch.countDown();
}
public static void main(String args[]) throws Exception {
CountDownLatch latch = new CountDownLatch(5);
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
service.execute(new ThreadDemo(latch));
}
latch.await();
Long total = 0L;
System.out.println(count);
for(Map.Entry<String, Long> s: count.entrySet()){
total += s.getValue();
}
System.out.println("all threads ended, " + " average cost is " + total
/ count.size());
}
}