理解Condition的用法
生活随笔
收集整理的這篇文章主要介紹了
理解Condition的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個示例中BoundedBuffer是一個固定長度的集合,這個在其put操作時,如果發現長度已經達到最大長度,那么會等待notFull信號,如果得到notFull信號會像集合中添加元素,并發出notEmpty的信號,而在其take方法中如果發現集合長度為空,那么會等待notEmpty的信號,同時如果拿到一個元素,那么會發出notFull的信號。
package locks;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class AppOfficial {
/**
* BoundedBuffer 是一個定長100的集合,當集合中沒有元素時,take方法需要等待,直到有元素時才返回元素
* 當其中的元素數達到最大值時,要等待直到元素被take之后才執行put的操作
* @author yukaizhao
*
*/
static class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
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() throws InterruptedException {
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();
return x;
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
final BoundedBuffer boundedBuffer = new BoundedBuffer();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
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(new Runnable() {
@Override
public void run() {
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();
}
}
總結
以上是生活随笔為你收集整理的理解Condition的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows Xp Sp3官方简体中文
- 下一篇: 【SAP业务模式】之STO(二):系统配