admin管理员组文章数量:1599408
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的操作
*@authoryukaizhao
**/
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");
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;
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;
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();
}
}
版权声明:本文标题:mysql中condition的用法_理解Condition的用法 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1728321799a1153921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论