转载

CountDownLatch和AtomicInteger

有一种场景:多个线程到达后才能执行某个任务,并且只能执行一次。

有几种方式:

1、Thread的join,不再讲解,因为使用不方便,也是不建议使用的方式。

2、AtomicInteger ,其increaseAndGet 是非常方便实现这个需求的。

3、CountDownLatch ,这个组件也可以,并且在特定场景下,这个是最好的实现,比如有时间等待限制的。

下面看这个2 和 3的case。

package a;  import java.util.concurrent.atomic.AtomicInteger;  /**  *   * @author xinchun.wang     @email: 532002108@qq.com  * @createTime 2015-4-2 下午11:25:26  */ public class AtomicExecute {  private static final int all = 3;   public static void main(String[] args) throws Exception {   AtomicInteger mask = new AtomicInteger(0);   TestThread t1 = new TestThread(mask);   TestThread t2 = new TestThread(mask);   TestThread t3 = new TestThread(mask);   System.out.println(t1.getName());   System.out.println(t2.getName());   System.out.println(t3.getName());   t1.start();   t2.start();   t3.start();  }   public static class TestThread extends Thread {   private final AtomicInteger mask;    public TestThread(AtomicInteger mask) {    this.mask = mask;   }    @Override   public void run() {        // do some things        if (mask.incrementAndGet() == all) {     System.out.println("running " + currentThread().getName());    }   }  }  }
package a;  import java.util.concurrent.CountDownLatch;  import a.T.TestThread2;  /**  *   * @author xinchun.wang     @email: 532002108@qq.com  * @createTime 2015-4-2 下午11:25:26  */ public class CountDown {  private static final int all = 3;  public static void main(String[] args) throws Exception {   CountDownLatch mask = new CountDownLatch(all);   TestThread t1 = new TestThread(mask);   TestThread t2 = new TestThread(mask);   TestThread t3 = new TestThread(mask);   TestThread2 t4 = new TestThread2(mask);   t4.start();   t1.start();   t2.start();   t3.start();  }   public static class TestThread2 extends Thread {   private final CountDownLatch mask;    public TestThread2(CountDownLatch mask) {    this.mask = mask;   }    @Override   public void run() {    System.out.println("comming " + currentThread().getName());    try {     mask.await();    } catch (InterruptedException e) {     e.printStackTrace();    }    // do target things    System.out.println("running " + currentThread().getName());   }  }    public static class TestThread extends Thread {   private final CountDownLatch mask;    public TestThread(CountDownLatch mask) {    this.mask = mask;   }    @Override   public void run() {    System.out.println("comming " + currentThread().getName());    // do some things    mask.countDown();   }  } }
正文到此结束
Loading...