Android之生产者与消费者
来源:互联网 发布:数据之巅在线阅读 编辑:程序博客网 时间:2024/06/05 16:33
本文主要记录一些零碎的东西
最近面试遇到的问题,代码写出生产者与消费者,只能说大学里学的都还给老师啦,其实事后一想,我们的项目里到处可见生产者消费者,其实这个模式就是一个容器 R 存共享资源,生产者A 在容器R还有空余时就放入产品,没有空余则等待容器R出现空余,消费者B在容器R有产品时 取出产品,没有产品时则等待容器R里出现产品,概念好理解,代码怎么实现
java测试代码
package com.example;public class MyClass { public static PublicResource resource = new PublicResource(); public static void main(String[] args){ new Thread(new ProducerThread(resource)).start(); new Thread(new ConsumerThread(resource)).start(); } public static class PublicResource { private int number = 0; /** * 增加公共资源 */ public synchronized void increace() { while (number != 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number++; System.out.println("ProducerThread->"+number); notify(); } /** * 减少公共资源 */ public synchronized void decreace() { while (number == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number--; System.out.println("ConsumerThread->"+number); notify(); } } public static class ProducerThread implements Runnable { private PublicResource resource; public ProducerThread(PublicResource resource) { this.resource = resource; } @Override public void run() { while (true) { resource.increace(); } } } /** * 消费者线程,负责消费公共资源 */ public static class ConsumerThread implements Runnable { private PublicResource resource; public ConsumerThread(PublicResource resource) { this.resource = resource; } @Override public void run() { while (true) { resource.decreace(); } } }}
无意中发现这篇文章,以Android里加载图片为例,学习了,看了代码还是敲的少了
0 0
- Android之生产者与消费者
- thread之消费者与生产者
- JAVA 多线程之生产者与消费者
- Java多线程之生产者与消费者
- java线程经典之生产者与消费者
- 多线程之生产者与消费者问题
- Java多线程之生产者与消费者
- 多线程经典之生产者与消费者
- Java多线程之 生产者与消费者
- 生产者与消费者之实现(wait、notify)
- 多线程之生产者与消费者模式
- 多线程之生产者与消费者问题
- 生产者与消费者之苹果橘子问题
- java多线程之生产者与消费者案例
- T626code学习笔记之生产者与消费者
- 多线程之生产者与消费者问题
- C语言之生产者与消费者模型
- 设计模式之:生产者与消费者模式
- ssh agent forward
- Xcode 常用快捷键及代码自动排版
- Errors running builder 'Validation' on project 'jumi_3.0'
- CSS3中背景的四个新的属性
- 线性回归与logistic回归的思路
- Android之生产者与消费者
- 自然语言处理之LSA
- C#获取本机IP搜集整理7种方法
- 配置eclipse使能打开当前文件所在目录
- HTML5
- linux中内存使用,swap,cache,buffer的含义总结
- Spring事务
- 部署opserver监控redis
- UVA 580 Critical Mass(递推)