当某项工作需要由若干项子任务并行地完成,并且只有在所有的子任务结束之后,当前主任务才能进入 下一阶段,这时候我们可以使用CountDownLatch。 CountDownLatch,直译为倒计数门阀,它的作用就与其名字所表达的意思一样,是指有一个门阀在等 待倒计数,直到计数器为0的时候才打开。
public class Test6 { public static void main(String[] args) { int[] productIds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; ListpriceList = Arrays.stream(productIds).mapToObj(ProductPrice::new).collect(Collectors.toList()); CyclicBarrier barrier = new CyclicBarrier(priceList.size()); List threadList = new ArrayList<>(); priceList.forEach(p -> { Thread thread = new Thread(() -> { try { System.out.println(p.getProductId() + "开始计算价格"); TimeUnit.SECONDS.sleep(new Random().nextInt(10)); p.setPrice(p.getProductId() * 0.9D); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }); threadList.add(thread); thread.start(); }); threadList.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println("所有商品价格计算完毕"); priceList.forEach(System.out::println); } private static class ProductPrice { private int productId; private double price; @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); sb.append(""productId":") .append(productId); sb.append(","price":") .append(price); sb.append('}'); return sb.toString(); } public ProductPrice(int productId) { this.productId = productId; } public ProductPrice(int productId, double price) { this.productId = productId; this.price = price; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)