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