CountDownLatch - 关于门闩的一个面试题

版权声明:本文为博主原创文章,欢迎转载,转载请注明本文链接! https://blog.csdn.net/qq_38238041/article/details/83789917
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
*/

猜你喜欢

转载自blog.csdn.net/qq_38238041/article/details/83789917