天天看點

JAVA多線程兩個實用的輔助類(CountDownLatch和AtomicBoolean)

AtomicBoolean它允許一個線程等待一個線程完成任務,然後運作:

A boolean value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicBoolean is used in applications such as atomically updated flags, and cannot be used as a replacement for a Boolean.      
public static void main(String[] args) {
    Thread t2 = new Thread(new BarWorker("bb"));
    Thread t1 = new Thread(new BarWorker("aa"));
    t2.run();
    t1.run();
  }


  private static class BarWorker implements Runnable {

    private static AtomicBoolean exists = new AtomicBoolean(false);

    private String name;

    public BarWorker(String name) {
      this.name = name;
    }

    public void run() {
      if (exists.compareAndSet(false, true)) {  //當第一個線程設定為true後,另外的線程是進不來的

        System.out.println(name + " enter"+"currentvalue="+exists.get());
        try {
          System.out.println(name + " working");
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          // do nothing
        }
        System.out.println(name + " leave");
        exists.set(false);
      } else {
        System.out.println(name + " give up");
      }
    }

  }      

列印的結果:

bb entercurrentvalue=true
bb working
bb leave
aa entercurrentvalue=true
aa working
aa leave      

CountDownLatch

一個同步輔助類。在完畢一組正在其它線程中運作的操作之前,它同意一個或多個線程一直等待。

假設設定  final CountDownLatch end = new CountDownLatch(10);  end.countDown();能夠降低計數

假設在某個地方寫  end.await();  假設計數不為0,全部線程會一直等待,計數不會被重置

private static  CountDownLatch mLatch = new CountDownLatch(5);

    public static void main(String[] args) throws InterruptedException {


        final ExecutorService exec = Executors.newFixedThreadPool(10);  

        for (int index = 0; index < 5; index++) {
            final int NO = index + 1;  
            Runnable run = new Runnable() {
                public void run() {  
                    try {  
                        System.out.println(NO + " working");
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {  
                    } finally {  
                        mLatch.countDown();
                    }  
                }  
            };  
            exec.submit(run);

        }  
        mLatch.await();  
        System.out.println("finish");  
        exec.shutdown();  
    }      

結果:

1 working
3 working
2 working
4 working
5 working
finish      

版權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。