这个是以前以前写的一个通过生产消费模式反应线程同步的一个案例
来源:互联网 发布:林建华 北大 知乎 编辑:程序博客网 时间:2024/04/29 14:18
import java.util.Random;
public class Demo13 {
public static void main(String[] args) {
final Oprations ops = new Oprations();
new Thread(new Runnable() {
@Override
public void run() {
//只生产5个
for (int i = 1; i <= 5; i++) {
ops.send();
}
}
}).start();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true){
//不管有没有生产都一直消费,因为只有生产了才能消费
ops.rec();
}
}
});
t.setDaemon(true);
t.start();
}
}
class Oprations{
private boolean flag;
int theValue;
/** 生产者 */
public void send() {
synchronized (this) {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
theValue = new Random().nextInt(1000);
System.out.println("send the value is:" + theValue);
flag = true;
this.notify();
}
}
/** 消费者 */
public void rec() {
synchronized (this) {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("receive the value is:" + theValue);
flag = false;
this.notify();
}
}
public class Demo13 {
public static void main(String[] args) {
final Oprations ops = new Oprations();
new Thread(new Runnable() {
@Override
public void run() {
//只生产5个
for (int i = 1; i <= 5; i++) {
ops.send();
}
}
}).start();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true){
//不管有没有生产都一直消费,因为只有生产了才能消费
ops.rec();
}
}
});
t.setDaemon(true);
t.start();
}
}
class Oprations{
private boolean flag;
int theValue;
/** 生产者 */
public void send() {
synchronized (this) {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
theValue = new Random().nextInt(1000);
System.out.println("send the value is:" + theValue);
flag = true;
this.notify();
}
}
/** 消费者 */
public void rec() {
synchronized (this) {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("receive the value is:" + theValue);
flag = false;
this.notify();
}
}
}
很多东西都记不太清楚了这几天翻来看了下,温故而知新
- 这个是以前以前写的一个通过生产消费模式反应线程同步的一个案例
- 线程的简单生产消费模式
- Kafka消息生产消费的一个java小案例(伪分布)
- 经典的生产与消费线程同步问题
- 消费和生产 二条线程同步 的例子
- 以前写的一个游戏~
- 整理修改的一个日志类,用生产与消费模式实现,消费模式用了异步执行
- 线程生产消费模式
- 通过生产-消费模型了解C#线程同步
- java线程同步----生产消费
- 以前写的一个大数计算器
- 以前写的一个文件夹遍历代码
- 共享一个以前写的俄罗斯方块
- 一个同步 锁的案例
- java线程的同步中notify和wait方法之生产消费实例讲解
- 生产消费模式的几种实现
- 【Java】----线程同步:生产-消费问题
- Java 线程同步 生产消费问题
- C++实例 自建基本mfc生成消息窗口和消息响应
- Android的JSON解析
- @@ManagedProperty注解
- C中的位段(位域)的使用
- 网站通用样式css代码
- 这个是以前以前写的一个通过生产消费模式反应线程同步的一个案例
- Oracle 11g(11.2.0) 手工建立数据库
- VMWare easy 模式安装Ubuntu 12.04时,停在installing vmware tools,please wait界面,解决方法
- SAP ERP业务优化之基于收货的发票验证
- NFC越来越近!关于NFC近场通讯的那些事儿
- JS实现进度条效果
- 今天开始博客写代码~
- 《深入浅出MFC》书中DECLARE_DYNAMIC/IMPLEMENT_DYNAMIC宏的详细解释
- Android Dependencies