import java.util.concurrent.locks.*;
class BoundedBuffer {
final Lock lock = new ReentrantLock();//对象锁
final Condition notFull = lock.newCondition(); //生产者监视器
final Condition notEmpty = lock.newCondition(); //消费者监视器
//资源对象
final Object[] items = new Object[10];
//putptr生产者角标,takeptr消费者角标,count计数器(容器的实际长度)
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
//生产者拿到锁
lock.lock();
try {
//当实际长度不满足容器的长度
while (count == items.length)
//生产者等待
notFull.await();
//把生产者产生对象加入容器
items[putptr] = x;
System.out.println(Thread.currentThread().getName()+" put-----------"+count);
Thread.sleep(1000);
//如果容器的实际长==容器的长,生产者角标置为0
if (++putptr == items.length) putptr = 0;
++count;
//唤醒消费者
notEmpty.signal();
} finally {
//释放锁
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
//消费者等待
notEmpty.await();
Object x = items[takeptr];
System.out.println(Thread.currentThread().getName()+" get-----------"+count);
Thread.sleep(1000);
if (++takeptr == items.length) takeptr = 0;
--count;
//唤醒生产者
notFull.signal();
return x;
} finally {
//释放锁
lock.unlock();
}
}
}
class Consu implements Runnable{
BoundedBuffer bbuf;
public Consu(BoundedBuffer bbuf) {
super();
this.bbuf = bbuf;
}
@Override
public void run() {
while(true){
try {
bbuf.take() ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Produ implements Runnable{
BoundedBuffer bbuf;
int i=0;
public Produ(BoundedBuffer bbuf) {
super();
this.bbuf = bbuf;
}
@Override
public void run() {
while(true){
try {
bbuf.put(new String(""+i++)) ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//主方法
class Lock1{
public static void main(String[] args) {
BoundedBuffer bbuf=new BoundedBuffer();
Consu c=new Consu(bbuf);
Produ p=new Produ(bbuf);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
Thread t3=new Thread(p);
Thread t4=new Thread(c);
t3.start();
t4.start();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有