我正在编写一个应用程序,需要从单个文件中读取块,每个块大约为 512 字节。我还需要同时写入块。
我的想法之一是BlockReader implements Runnable
and BlockWriter implements Runnable
and BlockManager
管理读者和作者。
我在发现的大多数示例中看到的问题是锁定问题和潜在的死锁情况。有什么想法如何实现这一点?
我会推荐这本书java并发实践 https://rads.stackoverflow.com/amzn/click/com/B000RH0EPC,在本例中为第 5.3 节(生产者-消费者模式)。
您的解决方案可能类似于:
BlockingQueue<Data> queue =
new LinkedBlockingQueue<Data>(MAX_BLOCKS_IN_QUEUE_UNTIL_BLOCK );
for (int i=0; i < MAX_DATA_PRODUCERS; i++ ) {
new Thread( new DataProducer( queue ) ).start();
}
new Thread(DataWriter( queue )).start
显然 DataProducer 和 DataWriter 是可运行的。
class DataProducer implements Runnable {
...
queue.put(data); // blocks if MAX_BLOCKS_IN_QUEUE_UNTIL_BLOCK
// are waiting to be written
// This prevents an OutOfMemoryException
...
}
class DataConsumer implements Runnable {
...
try {
while(true) {
writeData(queue.take()); // blocks until there is a block of data
}
} catch (InteruptedException e) {
Thread.currentThread().interrupt();
}
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)