package com.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//生产者消费模型
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource resource=new Resource();//资源对象
Producer producer=new Producer(resource);//生产者对象
Consumer consumer=new Consumer(resource);//消费者对象
//使用4个线程,模拟2个生产者,2个消费者
Thread t1=new Thread(consumer);
Thread t2=new Thread(producer);
Thread t3=new Thread(consumer);
Thread t4=new Thread(producer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count=1;
private boolean flag=false;
Lock lock=new ReentrantLock();
Condition con=lock.newCondition();
//生产出一个产品,并保证线程安全
public void set(String name){
lock.lock();//获取锁
//flag用于标记是否有产品,如果有则进入等待状态,并唤醒其他线程
try {
while(flag){
con.await();
}
this.name=name+"---"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag=true;
con.signalAll();
}catch (Exception e) {
}finally{
lock.unlock();//释放锁
}
}
//消耗一个产品,并保证线程安全
public void out(){
lock.lock();
while(!flag){
try {
con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"......消费者......"+this.name);
flag=false;
con.signalAll();
lock.unlock();
}
}
class Producer implements Runnable{
private Resource resource;
Producer(Resource resource){
this.resource=resource;
}
public void run() {
while(true){
resource.set("+商品+");
}
}
}
class Consumer implements Runnable{
private Resource resource;
Consumer(Resource resource){
this.resource=resource;
}
public void run() {
while(true){
resource.out();
}
}
}
|
|