Demo15_Condition实例

package test06;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo15_Condition实例 {

public static void main(String[] args) {
    BounderBuffer r = new BounderBuffer();

// 创建线程任务
Producer2 pro = new Producer2(r);
Consumer3 con = new Consumer3(r);
// 创建线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();

}

}
class BounderBuffer{
final Lock lock = new ReentrantLock();//锁
final Condition notFull = lock.newCondition();//生产
final Condition notEmpty = lock.newCondition();//消费
final Object[] items = new Object[100];//存储商品的容器
int putptr;//生产者角标
int takeptr;//消费者角标
int count;//计数器
// 生产者使用的方法,往数组中存储商品
public void put(Object x) throws InterruptedException{
lock.lock();
try{
while(count == items.length)//判断计数器是否已到数组长度,就将角标自动归零
notFull.await();
items[putptr] = x ;
if(++putptr == items.length)
putptr = 0 ;
++count ;//计数器自增

    System.out.println(Thread.currentThread().getName()+"...消费者..."+this.takeptr);
    notEmpty.signal();
}finally{
    lock.unlock();
}
}

public Object take()throws InterruptedException{
lock.lock();
try{
while(count == 0)//如果计数器为零,说明没有商品,消费者等待
notEmpty.await();
Object x = items[takeptr];//从数组中通过消费者角标获取商品
if(++takeptr == items.length)//判断消费者角标是否已到数组长度,就将角标自动归零
takeptr = 0 ;
–count ;//自减
System.out.println(Thread.currentThread().getName()+”…生产者…”+this.putptr);
notFull.signal();
return x ;
}finally{
lock.unlock();
}
}
}
class Producer2 implements Runnable
{
private BounderBuffer b ;
//生产者一初始化就有资源,需要将资源传递到构造函数中
Producer2(BounderBuffer b)
{
this.b = b ;
}
public void run()
{
while(true){
try {
b.put(“asdf”);
} catch (InterruptedException e) {
}
}
}
}
//描述消费者 处理资源
class Consumer3 implements Runnable
{
private BounderBuffer b ;
//消费者一初始化就有资源,需要将资源传递到构造函数中
Consumer3(BounderBuffer b)
{
this.b = b ;
}
public void run()
{
while(true)
{
try {
b.take();
} catch (InterruptedException e) {
}
}
}
}

猜你喜欢

转载自blog.csdn.net/mingxu_W/article/details/81742561
今日推荐