BoundedQueue
您可以使用接受说对象的条件来实现自定义100
,然后一次性编写。
现在您可以 BoundedQueue
与不同的线程共享这个类实例,这些线程会将对象放入其中,并且会有线程调用writeAll()
方法,直到您想要调用它。
BoundedBuffer boundedBuffer = new BoundedBuffer();
boundedBuffer.put("test"); .......
从写线程做下面
boundedBuffer.writeAll();
下面是示例代码
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition full = lock.newCondition();
final Condition empty = lock.newCondition();
final Object[] items = new Object[100];
int count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) {
empty.signal();
full.await();
}
items[count] = x;
++count;
} finally {
lock.unlock();
}
}
public void writeAll() throws InterruptedException {
lock.lock();
try {
while (count < items.length)
empty.await();
// Write to file here After write finished signal full condition
count = 0;
full.signal();
} finally {
lock.unlock();
}
}
}