如何使用java中的线程读取和写入文件? [英] How do I read and write to a file using threads in java?

查看:545
本文介绍了如何使用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?

推荐答案

我会推荐这本书 java Concurrency in Practice ,在本例中为第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中的线程读取和写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆