如何使用预定义的部分(按行号)将多个线程写入单个文件?

时间:2016-09-01 05:08:24

标签: java multithreading algorithm

假设我有5个线程,并且已经在与线程关联的文件中预先分配了行号,例如线程1写入行号。 1到5,线程2写入6到10 ...线程5写入21到25.我想编写一个可以并行方式执行此操作的Java程序(即不通过单个线程锁定文件)

1 个答案:

答案 0 :(得分:0)

Your best bet here will be to use NIO API's that are available in Java. Specifically you will be interested in FileChannel

Just to quote the documentation here , in the interest of whats important

A file channel is a SeekableByteChannel that is connected to a file. It has a current position within its file which can be both queried and modified. The file itself contains a variable-length sequence of bytes that can be read and written and whose current size can be queried.

A region of a file may be locked against access by other programs.

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface.