CountDownLacth的使用

来源:互联网 发布:mac锁屏快捷键 编辑:程序博客网 时间:2024/06/14 10:35
package myAllTest.TCountDownLatch;
import java.util.concurrent.CountDownLatch;
public class TCountDownLatch {
 /**
  *
  * 这个类的作用是为了测试一下CountDownLacth这个类
  * 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
  * @param args
  */
 public static void main(String[] args) {
  TCountDownLatch td=new TCountDownLatch();
  CountDownLatch latch=new CountDownLatch(2);
  Worker work1=td.new Worker("bb",latch);
  Worker work2=td.new Worker("aa",latch);
  work1.start();
  work2.start();
//  try {
//   latch.await();
//  } catch (InterruptedException e) {
//   // TODO Auto-generated catch block
//   e.printStackTrace();
//  }
  System.out.println("结束");
  
 }
 class Worker extends Thread
 {
  private String name;
  private CountDownLatch latch;
  
  public Worker(String name,CountDownLatch latch) {
   // TODO Auto-generated constructor stub
   this.name=name;
   this.latch=latch;
  }
  
  @Override
  public void run() {
   // TODO Auto-generated method stub
   System.out.println("name: "+name+" in");
   this.delay();
   System.out.println("name: "+name+" out");
   //完成工作计数器减一
   latch.countDown();
  }
  
  public void delay()
  {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  
 }
 
 
}

这个时将注释去掉之后的结果

原创粉丝点击