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

來源:互聯網
上載者:User

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=truebb workingbb leaveaa entercurrentvalue=trueaa workingaa 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 working3 working2 working4 working5 workingfinish






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.