📄 boundedbuffer.java
字号:
package thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedBuffer {
static final int PutInterval=15000;
static final int TakeInterval=40000;
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final static int BufferSize=10;
final Object[] buffer = new Object[BufferSize];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
System.out.println("put: waiting lock...");
lock.lock();
System.out.println("put: locked and wait notFull ...");
try {
while (count == buffer.length)
notFull.await();
System.out.println("put: count="+(count+1));
buffer[putptr] = x;
if (++putptr == buffer.length) putptr = 0;
++count;
notEmpty.signal();
System.out.println("Put: sleeping...");
Thread.sleep(PutInterval);
}
finally {
lock.unlock();
System.out.println("put: unlock");
}
}
public Object take() throws InterruptedException {
System.out.println("take: waiting lock ... ");
lock.lock();
System.out.println("take: locked and wait for notEmpty ... ");
try {
while (count == 0)
notEmpty.await();
System.out.println("take: count="+(count-1));
Object x = buffer[takeptr];
if (++takeptr == buffer.length) takeptr = 0;
--count;
notFull.signal();
System.out.println("Take: sleeping...");
Thread.sleep(PutInterval);
return x;
} finally {
lock.unlock();
System.out.println("take: unlock");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -