线程问题<2>
来源:互联网 发布:模拟人生2数据丢失 编辑:程序博客网 时间:2024/06/15 21:26
面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法
能够支持2个生产者线程以及10个消费者线程的阻塞调用
1.使用wait和notify/notifyAll来实现
public class Test<T> {private LinkedList<T> list = new LinkedList<T>();private int MAX = 10;//最大容量private int count = 0;//当前容器的个数public synchronized void put(T t) {while(list.size() == MAX) {try {System.out.println("生产者进入了等待");this.wait();} catch (InterruptedException e) {e.printStackTrace();}}list.add(t);System.out.println("生产者生产了" + t);++count;this.notifyAll();}public synchronized <T> T get() {T t = null;while(list.size() == 0) {try {System.out.println("消费者进入了等待");this.wait();} catch (InterruptedException e) {e.printStackTrace();}}t = (T) list.removeFirst();System.out.println("消费者消费了" + t); --count;this.notifyAll();return t;}public static void main(String[] args) throws InterruptedException {final Test test = new Test();for (int i = 0; i < 10; i++) {new Thread() {public void run() {for (int j = 0; j < 5; j++) {test.get();}}}.start();}for (int i = 0; i < 2; i++) {new Thread() {public void run() {for (int j = 0; j < 35; j++) {test.put(j);}}}.start();}Thread.sleep(1000);System.out.println("容器中还有" + test.count + "个");}}
2.使用Lock和Condition来实现
public class Test51<T> {final private LinkedList<T> list = new LinkedList();private static int MAX = 10;private int count = 0;private Lock lock = new ReentrantLock();private Condition p = lock.newCondition();private Condition c = lock.newCondition();public void put(T t) {try {lock.lock();while(list.size() == MAX) {System.out.println("生产者进入等待");p.await();}list.add(t);System.out.println("生产者生产了" + t);++count;c.signalAll();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}public <T> T get() {T t = null;try {lock.lock();while(list.size() == 0) {System.out.println("消费者进入等待");c.await();}t = (T) list.removeFirst();System.out.println("消费者消费了" + t);--count;p.signalAll();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}return t;}public static void main(String[] args) throws InterruptedException {final Test51 t = new Test51();for (int i = 0; i < 10; i++) {new Thread() {public void run() {for (int j = 0; j < 5; j++) {t.get();}}}.start();}for (int i = 0; i < 2; i++) {new Thread() {public void run() {for (int j = 0; j < 25; j++) {t.put(j);}}}.start();}Thread.sleep(1000);System.out.println("还剩余" + t.count);}}
阅读全文
0 0
- 线程同步问题2
- 线程问题<2>
- tomcat中的线程问题2
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- 线程问题
- PrefixHeader文件、NSLog在release下不打印
- Java
- android 内存优化面试知识
- RecyclerView复杂布局动态管理GridLayoutManager
- android代码里的分区信息
- 线程问题<2>
- 使用PlupLoad js插件进行文件上传案例
- ubuntu下使用Anaconda应用:创建虚拟环境实现python不同版本切换、科学计算工具包安装
- maven环境安装(Mac版)
- 理解LSTM网络【译】
- java 内部类
- 关于在for循环中绑定事件打印变量i是最后一次
- Android 支付宝支付开发流程
- HardFault 异常定位