Java 多线程 CountDownLatch

Java 多线程 CountDownLatch

package thread.latch;

import java.util.concurrent.CountDownLatch;

public class Leader implements Runnable {
  private CountDownLatch downLatch;

  public Leader(CountDownLatch downLatch) {
    this.downLatch = downLatch;
  }

  public void run() {
    System.out.println("leader 正在等所有的worker把活干完。");
    try {
      this.downLatch.await();
    } catch (InterruptedException e) {
    }
    System.out.println("worker 把活都干完了,leader 开始检查了。");
  }
}
package thread.latch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable {
  private CountDownLatch downLatch;
  private String name;
  private String workContent;

  public Worker(CountDownLatch downLatch, String name, String workContent) {
    this.downLatch = downLatch;
    this.name = name;
    this.workContent = workContent;
  }

  public void run() {
    this.doSomething();
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException ie) {
    }
    System.out.println(this.name + " " + workContent + " 做完了");
    this.downLatch.countDown();
  }

  private void doSomething() {
    System.out.println(this.name + " 正在 " + workContent);
  }

}
package thread.latch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
  
  /**
   * @author jzh add 2011-12-25
   * @param args
   */
  public static void main(String[] args) {
    // 创建一个线程池(创建一个可根据需要创建新线程的线程池)
    // Executors 类提供了用于此包中所提供的执行程序服务的工厂方法
    ExecutorService pool = Executors.newCachedThreadPool();

    // 初始化一个4次的CountDownLatch
    CountDownLatch latch = new CountDownLatch(4);
    
    Worker wroker1 = new Worker(latch, "chanpinxue.cn", "扫地");
    Worker wroker2 = new Worker(latch, "jiang", "擦桌子");
    Worker wroker3 = new Worker(latch, "jzh", "洗碗");
    Worker wroker4 = new Worker(latch, "jiangzhihao", "关窗");

    Leader leader = new Leader(latch);

    pool.execute(wroker1);
    pool.execute(wroker2);
    pool.execute(wroker3);
    pool.execute(wroker4);

    pool.execute(leader);

    pool.shutdown();

  }

}

 

发表回复

您的电子邮箱地址不会被公开。