生产者和消费者
来源:互联网 发布:社交网络发展的好处 编辑:程序博客网 时间:2024/05/29 14:35
生产者和消费者
/*生产者和消费者指的是两个不同的线程对象操作同一资源的情况生产者负责生产数据,消费者负责取走数据生产者生产完一组数据,消费者就要取走一组数据防止重复数据,必须加入等待wait()和唤醒notify(),等待wait(),唤醒第一个等待线程notify(),唤醒全部等待线程,哪个优先级高就先执行哪个notifyAll(),sleep()和wait()的区别,sleep是Thread定义的类,而wait()是Object定义的类,sleep(),可以设置休眠时间,时间一到自动唤醒,而wait()需要等待notify进行唤醒*/
class Info{ private String titie; private String content; private boolean flag=true; //flag=true:表示可以生产数据,但是不能取走数据 //flag=false;表示可以取走数据,但是不能生产数据 public synchronized void set(String titie,String content){ if(!this.flag){ try { super.wait();//等待 } catch (InterruptedException e) { e.printStackTrace(); } } this.titie=titie; try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } this.content=content; this.flag=false;//修改生产状态 super.notify();//唤醒其他等待线程 } public synchronized void get(){ if(this.flag){ try { super.wait();//等待 } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.titie+" - "+this.content); this.flag=true;//修改消费状态 super.notify();//唤醒其他等待线程 }}class Productor implements Runnable{ private Info info; public Productor(Info info){ this.info=info; } @Override public void run() { for (int i = 0; i < 100; i++) { if(i%2==0){//生产数据 this.info.set("偶数","设置的是偶数"); }else{ this.info.set("奇数","设置的是奇数"); } } }}class Consumer implements Runnable{ private Info info; public Consumer(Info info){ this.info=info; } @Override public void run() { for (int i = 0; i < 100; i++) { this.info.get();//消费者获取数据 } }}public class testController{ public static void main(String[] args) { Info info =new Info(); new Thread(new Productor(info)).start(); new Thread(new Consumer(info)).start(); }}
阅读全文
0 0
- 生产者和消费者
- 生产者和消费者
- 消费者和生产者问题
- 生产者和消费者
- pv 生产者和消费者
- 生产者和消费者
- 生产者和消费者
- java 生产者和消费者
- 多线程生产者和消费者
- 生产者和消费者问题
- 生产者和消费者
- 生产者和消费者问题
- 生产者和消费者模拟
- 生产者和消费者问题
- 生产者和消费者模式
- 消费者和生产者问题
- 生产者和消费者
- 生产者和消费者
- 十大基础排序 · 九 --- 桶排序(不稳定)
- 阿里开放搜索 python的API简单封装
- 如何将node.js应用程序部署到Heroku
- Python pip 常用命令
- 推荐六个免费在线生成网址二维码的API接口
- 生产者和消费者
- 棋盘(Checkerboard)算法
- C++之宁以pass-by-reference-to-const替换pass-by-value(20)---《Effecitive C++》
- tensorflow使用遇到的问题The TensorFlow library wasn't compiled to use SSE instructions, but these are avail
- 49. Group Anagrams
- BZOJ 1180: [CROATIAN2009]OTOCI (LCT题解)
- 第10节-Linux文件系统与目录树得关系
- CSS属性之浮动flow
- CTF中常用的zio模块笔记