这个是以前以前写的一个通过生产消费模式反应线程同步的一个案例
2013-03-06 17:28
302 查看
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();
}
}
}
很多东西都记不太清楚了这几天翻来看了下,温故而知新
相关文章推荐
- 通过生产-消费模型了解C#线程同步
- 整理修改的一个日志类,用生产与消费模式实现,消费模式用了异步执行
- 2.RABBITMQ 入门 - WINDOWS - 生产和消费消息 一个完整案例
- Kafka消息生产消费的一个java小案例(伪分布)
- 在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。
- 通过pthread_mutex_lock和pthread_cond_wait实现生产消费模式,并且生产一次消费一次
- 通过脚本案例学习shell(五) 通过创建DNS脚本一步一步教你将一个普通脚本规范到一个生产环境脚本 推荐
- RocketMQ使用P2P(点对点)消息传送模式,生产端生产一个消息,消费端消费几乎同时收到两个相同消息
- blockingQueue实现消费-生产模式
- 生产消费者4 - 实现一个基于优先级的传输队列【消费顺序是由优先级决定的而不是抵达时间】
- C# 关于委托和事件的妙文:通过一个例子详细介绍委托和事件的作用;Observer模式简介
- 线程的简单生产消费模式
- Java 线程同步 生产消费问题
- C# 关于委托和事件的妙文:通过一个例子详细介绍委托和事件的作用;Observer模式简介
- 使用C#的泛型队列Queue实现生产消费模式
- 《Orange’s 一个操作系统的实现》3.保护模式7-特权级转移(通过调用门转移目标段-有特权级转换-理论)
- 0015-多线程-生产消费模式
- 定义一个单例模式的类,在这个类中,只有唯一的实例,不能new出来其他的实例对象。
- GCD 实现生产-消费 模式
- 每日一个js实例13--通过曲线反应json数据