Java多线程有序写同一个文件
时间: 2024-09-30 16:10:56 浏览: 32
在Java中,如果多个线程需要顺序写入同一个文件,通常会采用锁(Locking)机制来保证数据的一致性和完整性。最常用的是使用`synchronized`关键字或者`java.util.concurrent.locks.ReentrantReadWriteLock`。这里是一个简单的例子:
```java
import java.io.FileWriter;
import java.io.IOException;
public class ThreadSafeWriter {
private static final Object lock = new Object();
private static FileWriter writer;
public synchronized void openFile(String fileName) throws IOException {
if (writer == null) {
writer = new FileWriter(fileName);
}
}
public synchronized void writeLine(String line) {
try {
writer.append(line + "\n");
} catch (IOException e) {
// Handle exception
}
}
public synchronized void closeFile() throws IOException {
writer.close();
writer = null;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
ThreadSafeWriter writer = new ThreadSafeWriter();
Thread t1 = new Thread(() -> {
writer.openFile("file.txt");
for (int i = 0; i < 5; i++) {
writer.writeLine("Thread 1: " + i);
}
writer.closeFile();
});
Thread t2 = new Thread(() -> {
writer.openFile("file.txt"); // 这里会阻塞直到t1释放锁
for (int i = 5; i < 10; i++) {
writer.writeLine("Thread 2: " + i);
}
writer.closeFile();
});
t1.start();
t2.start();
t1.join();
t2.join(); // 等待两个线程完成
}
}
```
在这个例子中,通过`synchronized`关键字,我们保证了对文件操作的独占访问,每个线程在打开、写入和关闭文件时都会获得锁,从而实现了有序写入。
阅读全文