本文介绍了如何使用java中的线程读取和写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在编写一个应用程序,我需要从单个文件读取块,每个块大约512字节。我还需要同时编写块。

I'm writing an application where I need to read blocks in from a single file, each block is roughly 512 bytes. I am also needing to write blocks simultaneously.

我的一个想法是 BlockReader实现了Runnable BlockWriter实现Runnable BlockManager 管理读者和作者。

One of the ideas I had was BlockReader implements Runnable and BlockWriter implements Runnable and BlockManager manages both the reader and writer.

我发现的大多数示例中遇到的问题是锁定问题和潜在的死锁情况。任何想法如何实现这个?

The problem that I am seeing with most examples that I have found was locking problems and potential deadlock situations. Any ideas how to implement this?

推荐答案

我会推荐这本书,在本例中为第5.3节(生产者 - 消费者模式)。

I would recommend the book java Concurrency in Practice, in this case section 5.3 (Producer-consumer pattern).

您的解决方案可能类似于:

your solution could look something like:

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是可运行的。

Obviously DataProducer and DataWriter are runnables.

 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();
   }
   ...
 }

这篇关于如何使用java中的线程读取和写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 05:49