CountDownLatch - 關於門閂的一個面試題
阿新 • • 發佈:2018-11-11
package concurrent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * 面試題:實現一個容器,提供兩個方法,一個size,一個add * 寫兩個執行緒,執行緒1往自定義容器中新增十個元素,執行緒2實時監控容器中的數量, * 在容器中元素個數為5的時候輸出並結束執行緒 * 使用門閂,門閂初始為1,當變為0的時候門閂開啟,執行緒2就受到了通知,輸出並結束 * @author BarryLee * @2018年11月6日@下午12:49:52 */ public class TestCountDowmLauch { volatile List<Object> list = new ArrayList<>(); void add(Object o) { list.add(o); } int size() { return list.size(); } public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(1);// TestCountDowmLauch container = new TestCountDowmLauch();// 自定義的容器 new Thread(new Runnable() { @Override public void run() { if (container.size() != 5) { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("thread2 - end"); } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { if (container.size() == 5) { latch.countDown(); } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread1 - add"); container.add(new Object()); } } }).start(); } } /* thread1 - add thread1 - add thread1 - add thread1 - add thread1 - add thread2 - end thread1 - add thread1 - add thread1 - add thread1 - add thread1 - add */