Java使用锁机制多线程写文件
时间: 2024-01-06 13:06:12 浏览: 39
使用锁机制可以保证多个线程同时写同一个文件时不会出现数据错乱的情况。在Java中,可以使用 `synchronized` 关键字来实现锁机制。下面是一个Java多线程写文件并使用锁机制的示例代码:
```java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterThread extends Thread {
private FileWriter writer;
private String data;
public FileWriterThread(FileWriter writer, String data) {
this.writer = writer;
this.data = data;
}
public void run() {
synchronized (writer) {
try {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
FileWriter writer = null;
try {
writer = new FileWriter("test.txt");
for (int i = 0; i < 10; i++) {
FileWriterThread thread = new FileWriterThread(writer, "thread " + i + "\n");
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
在这个示例中,我们在 `run` 方法中使用 `synchronized` 关键字来获取 `writer` 对象的锁,然后执行写入操作。这样就可以保证多个线程同时写同一个文件时不会出现数据错乱的情况。