我正在創建一個多線程服務器,並且我創建了一個類來管理用戶,但我注意到當一個線程正在讀取文件時,我的UserManager類可能會導致錯誤,並且其他的是寫入文件,如何防止它?Java多線程阻止兩個函數同時運行
package server.questiongiver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.ArrayList;
import server.engine.CustomLog;
public class UserManager {
public static User loadUser(String id, Socket s) {
User user = null;
if (id == null) {
return user;
}
File f = new File("users.dat");
if (f.isFile() && f.canRead()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
if (line.equals("[" + id + "]")) {
user = new User(s);
user.id = id;
user.password = br.readLine().split("-separator-")[1];
user.username = br.readLine().split("-separator-")[1];
break;
}
}
}
catch (IOException ex) {
CustomLog.error(ex.getMessage());
}
}
return user;
}
public static ArrayList<User> loadAllUsers() {
File f = new File("users.dat");
ArrayList<User> users = new ArrayList();
if (f.isFile() && f.canRead()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
if (line.matches("^(\\[[0-9]*\\])$")) {
User user = new User(null);
user.id = line.replace("[", "").replace("]", "");
user.password = br.readLine().split("-separator-")[1];
user.username = br.readLine().split("-separator-")[1];
users.add(user);
}
}
}
catch (IOException ex) {
CustomLog.error(ex.getMessage());
}
}
return users;
}
public static void saveUser(User user) {
File f = new File("users.dat");
String content = "";
String newLine = System.getProperty("line.separator");
boolean found = false;
if (f.isFile() && f.canRead()) {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) {
if (line.equals("[" + user.id + "]") && br.readLine().equals(user.password)) {
found = true;
content += "[" + user.id + "]" + newLine;
content += "password-separator-" + user.password + newLine;
content += "username-separator-" + user.username + newLine;
br.readLine();
}
else {
content += line + newLine;
}
}
}
catch (IOException ex) {
CustomLog.error(ex.getMessage());
}
}
if (!found) {
content += "[" + user.id + "]" + newLine;
content += "password-separator-" + user.password + newLine;
content += "username-separator-" + user.username + newLine;
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(f))) {
writer.write(content);
writer.close();
}
catch (FileNotFoundException | UnsupportedEncodingException ex) {
CustomLog.error(ex.getMessage());
}
catch (IOException ex) {
CustomLog.error(ex.getMessage());
}
}
}
如果您使用Java 7+,爲什麼使用'File'?使用java.nio.file代替 – fge