生产者消费者:等待唤醒机制(最终版代码)
来源:互联网 发布:淘宝9.9包邮网 编辑:程序博客网 时间:2024/05/17 06:05
public classStudent {
private Stringname;
private int age;
private boolean flag; // 默认情况是没有数据,如果是true,说明有数据
public synchronized void set(String name,int age) {
// 如果有数据,就等待
if (this.flag) {
try {
this.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
// 设置数据
this.name = name;
this.age = age;
// 修改标记
this.flag =true;
this.notify();
}
public synchronized void get() {
// 如果没有数据,就等待
if (!this.flag) {
try {
this.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
// 获取数据
System.out.println(this.name +"---" + this.age);
// 修改标记
this.flag =false;
this.notify();
}
}
public classSetThread implementsRunnable {
private Students;
private int x = 0;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
s.set("林青霞", 27);
}else{
s.set("刘意", 30);
}
x++;
}
}
}
public classGetThread implementsRunnable {
private Students;
public GetThread(Students) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
}
/**
* 最终版代码中:
* 把Student的成员变量给私有的了。
* 把设置和获取的操作给封装成了功能,并加了同步。
* 设置或者获取的线程里面只需要调用方法即可。
*/
public classStudentDemo {
public static void main(String[] args) {
//创建资源
Students = newStudent();
//设置和获取的类
SetThreadst = newSetThread(s);
GetThreadgt = newGetThread(s);
//线程类
Threadt1 = newThread(st);
Threadt2 = newThread(gt);
//启动线程
t1.start();
t2.start();
}
}
- 生产者消费者:等待唤醒机制(最终版代码)
- 线程的等待唤醒机制(生产者消费者代码)
- 多线程_生产者消费者之等待唤醒机制代码实现
- 多线程_生产者消费者之等待唤醒机制代码分析
- 多线程_生产者消费者之等待唤醒机制代码优化
- 多线程-生产者消费者之等待唤醒机制代码优化
- 线程间通信:生产者消费者(等待唤醒机制)
- 生产者和消费者之等待唤醒机制
- 多线程-生产者消费者之等待唤醒机制
- 多线程-等待唤醒机制经典案例-生产者消费者
- 多线程_生产者消费者之等待唤醒机制思路图解
- 多线程——等待唤醒机制经典实例:生产者消费者模式(优化)
- java多线程(2):线程通信之生产者消费者模式及等待唤醒机制
- 通过生产者消费者案例理解等待唤醒机制和虚假唤醒
- Java多线程生产者消费者说明等待唤醒机制问题和虚假唤醒问题
- 多生产者和多消费者等待唤醒
- java多线程中的等待唤醒机制--多生产者多消费者问题
- java多线程之 生产者和消费者 线程间通信 等待与唤醒机制
- 【DirectX11】第二篇 DirectX11渲染管线(2016.05.09更新)
- 深入学习Fragment
- njust 1925 sequence 拆分序列,寻找非降序列的最小个数,不变序列顺序。
- 实验二:ARM指令
- python中的list http://www.jb51.net/article/47978.htm
- 生产者消费者:等待唤醒机制(最终版代码)
- 如何将dockerhub与github关联
- 操作系统整理
- 心急的C小加
- 为什么size_t重要?
- iOS-判断URL是否可用,判断网址是否正确
- 想玩好嵌入式,你需要关注以下几个方面
- Android API 23中废弃了HttpClient的解决办法
- js 控制 checkbox不选中