import java.util.concurrent.locks.*;
class BoundedBuffer {
private final Lock lock = new ReentrantLock();
//创建监视器对象,每个监视器对象对应一个FIFO队列
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
//容器
private final int[] items = new int[100];
private int putptr, takeptr, count;//容器角标 数量
public void put() throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = putptr;//填充数字
if (++putptr == items.length) putptr = 0;
++count;
System.out.println(Thread.currentThread().getName()+"---生产第"+putptr+"个容器里的----总共"+count);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public void take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
takeptr = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
System.out.println(Thread.currentThread().getName()+"---消费第"+takeptr+"个容器里的----还剩"+count);
notFull.signal();
} finally {
lock.unlock();
}
}
}
//2.描述生产者
class Produce implements Runnable{
private BoundedBuffer b;
//生产者一初始化就要有资源,需要将资源传递到构造函数中。
Produce(BoundedBuffer b){
this.b = b;
}
@Override
public void run() {
while (true){
try {
b.put();
}catch (InterruptedException e){}
}
}
}
//3.描述消费者
class Consume implements Runnable{
private BoundedBuffer b;
//消费者一初始化就要有资源,需要将资源传递到构造函数中。
Consume(BoundedBuffer b){
this.b = b;
}
@Override
public void run() {
while (true){
try {
b.take();
}catch (InterruptedException e){}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
BoundedBuffer b = new BoundedBuffer();
Produce pro = new Produce(b);
Consume con = new Consume(b);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
多生产多消费
最新推荐文章于 2021-06-12 17:24:03 发布