java多线程lock notify_【Java多线程通信】syncrhoized下wait()/notify()与ReentrantLock下condition的用法比较...

packagelocks;importjava.util.Random;importjava.util.concurrent.locks.Condition;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;public classAppOfficial {/*** BoundedBuffer 是一个定长100的集合,当集合中没有元素,take方法需要等待,直到有元素时才返回元素

* 当集合满了,要等待直到元素被take之后才执行put的操作*/

static classBoundedBuffer {//定义一个锁对象

final Lock lock = newReentrantLock();//定义两种被唤醒的条件:非满、非空

final Condition notFull =lock.newCondition();final Condition notEmpty =lock.newCondition();final Object[] items = new Object[100];intputptr, takeptr, count;public void put(Object x) throwsInterruptedException {

System .out.println("put wait lock");//加锁进行put操作

lock.lock();

System.out.println("put get lock");try{//当集合满了,则等待 非满 情况的发生

while (count ==items.length) {

System.out.println("buffer full, please wait");

//在 非满 条件下挂起,等待非满条件的唤醒操作才继续执行下去

notFull.await();

}

items[putptr]=x;if (++putptr ==items.length)

putptr= 0;++count;//执行完插入操作后,集合非空,通知 非空 条件下挂起的线程 可以继续进行take操作了

notEmpty.signal();

}finally{

lock.unlock();

}

}public Object take() throwsInterruptedException {

System.out.println("take wait lock");

lock.lock();

System.out.println("take get lock");try{while (count == 0) {

System.out.println("no elements, please wait");

//在 非空 条件下挂起

notEmpty.await();

}

Object x=items[takeptr];if (++takeptr ==items.length)

takeptr= 0;--count;//集合不是满的了,唤醒在 非满 情况下挂起的put线程可以继续执行put操作

notFull.signal();returnx;

}finally{

lock.unlock();

}

}

}public static voidmain(String[] args) {final BoundedBuffer boundedBuffer = newBoundedBuffer();

Thread t1= new Thread(newRunnable() {

@Overridepublic voidrun() {

System.out.println("t1 run");for (int i=0;i<1000;i++) {try{

System.out.println("putting..");

boundedBuffer.put(Integer.valueOf(i));

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}) ;

Thread t2= new Thread(newRunnable() {

@Overridepublic voidrun() {for (int i=0;i<1000;i++) {try{

Object val=boundedBuffer.take();

System.out.println(val);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}) ;

t1.start();

t2.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值