赞
踩
生产者消费者
一个最简单的模型。两个线程,一个生产者,一个消费者,生产者负责生产,消费者负责消费。
分析:
同步:生产者生产了之后,消费者进行读取数据。wait 和notify机制
互斥:生产者生产时,消费者不能进行读取。锁机制。
public class ProducerAndConsumer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource s = new Resource();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
new Thread(p).start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(c).start();
}
}
//定义资源
class Resource{
boolean flag =false;
public synchronized void produce(){
if(!flag){
System.out.println("producer:i hava produce");
flag = true;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void consume(){
if (flag) {
System.out.println("consumer:i have consume");
flag = false;
this.notify();
} else {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//生产者
class Producer implements Runnable{
private Resource s;
Producer(Resource s){
this.s = s;
}
public void run(){
while (true) {
s.produce();
}
}
}
//消费者
class Consumer implements Runnable{
private Resource s;
Consumer(Resource s){
this.s = s;
}
public void run(){
while(true){
s.consume();
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。