War*_*les 2 java multithreading java-io
我正在编写一个应用程序,我需要从单个文件中读取块,每个块大约 512 字节。我还需要同时写入块。
其中一个想法我是BlockReader implements Runnable和BlockWriter implements Runnable并BlockManager同时管理读写器。
我在我发现的大多数示例中看到的问题是锁定问题和潜在的死锁情况。任何想法如何实现这一点?
我会推荐这本书java Concurrency in Practice,在这种情况下是第 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
Run Code Online (Sandbox Code Playgroud)
显然 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();
}
...
}
Run Code Online (Sandbox Code Playgroud)