main thread starting…

本文提供了一个使用 Java 中 CountDownLatch 类的示例程序。通过创建多个线程并利用 CountDownLatch 进行同步,演示了如何等待所有子线程完成后再继续执行主线程。此示例有助于理解 CountDownLatch 的基本用法。

 执行结果例如以下:

  main thread starting…

  Thrad 2 staring…

  Thrad 2 end…

  Thrad 4 staring…

  Thrad 4 end…

  Thrad 1 staring…

  Thrad 1 end…

  Thrad 3 staring…

  Thrad 3 end…

  Thrad 5 staring…

  Thrad 5 end…

  main thread end…

  CountDownLatch方式代码例如以下:

  package com.test.thread;

  import java.util.concurrent.CountDownLatch;

  public class MyThread2 extends Thread

  {

  private CountDownLatch count;

  public MyThread2(CountDownLatch count, String name)

  {

  this.count = count;

  this.setName(name);

  }

  @Override

  public void run()

  {

  System.out.println(this.getName() + " staring…");

  System.out.println(this.getName() + " end…")。

  this.count.countDown();

  }

  /**

  * @param args

  */

  public static void main(String[] args)

  {

  System.out.println("main thread starting…");

  CountDownLatch count = new CountDownLatch(5);

  for (int i = 1; i <= 5; i++)

  {

  MyThread2 my = new MyThread2(count, "Thread " + i);

  my.start()。

  }

  try

  {

  count.await();

  }

  catch (InterruptedException e)

  {

  e.printStackTrace();

  }

  System.out.println("main thread end…");

  }

  }

  执行结果例如以下:

  main thread starting…

  Thread 2 staring…

  Thread 2 end…

  Thread 4 staring…

  Thread 4 end…

  Thread 1 staring…

  Thread 1 end…

  Thread 3 staring…

  Thread 3 end…

  Thread 5 staring…

  Thread 5 end…

  main thread end…

转载于:https://www.cnblogs.com/claireyuancy/p/7100786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值