![](/img/trans.png)
[英]How to synchronize file writing to achieve maximum concurrency between threads Java
[英]How to synchronize multiple threads writing into a file
我正在使用ExecutorService
使多個線程將文本寫入文件,但我無法設法同步run()
方法,而不是我問的是正確的逐行字符串,而是混合了字符串的所有字符因為他們是同時寫的。
import java.io.BufferedReader
...
class WriteDns implements Runnable {
File file;
String text;
WriteDns(File file, String text) {
this.file = file;
this.text = text;
}
public void run() {
synchronized (this) {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)))) {
bw.write(turnDns() + "\n");
} catch (IOException e) {
System.out.println("Error");
}
}
}
public String turnDns() {
int space = text.indexOf(' ');
String ip = text.substring(0, space);
String theRest = text.substring(space);
String temp = ip;
try {
ip = InetAddress.getByName(ip).getHostName();
if (ip == temp)
return "NotFound " + theRest;
return ip + " " + theRest;
} catch (UnknownHostException e) {
System.out.println("Error in change");
return "-changeErr " + theRest;
}
}
}
public class Main00 {
static File oldFile = new File("oldfile.txt");
public static void main(String[] args) {
readLines();
}
public static void readLines() {
try (BufferedReader br = new BufferedReader(new FileReader(oldFile))) {
File f = new File("file.txt");
ExecutorService service = Executors.newFixedThreadPool(10);
for (String t = br.readLine(); t != null; t = br.readLine()) {
service.execute(new WriteDns(f, t));
}
service.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
}
您正在this
同步,但是您正在為每個線程創建線程工作器的新實例,因此每個線程都鎖定在自己身上,從不等待任何其他線程。 您需要鎖定一個對所有線程可見的對象,可能是靜態對象,或者在實例化WriteDns
時傳遞一個鎖定對象。
話雖如此,在一個文件上打開多個線程本質上很容易出現您遇到的問題,並且由於瓶頸是您的存儲介質,而不是處理器,因此編寫多個線程並不會帶來任何好處。 您應該有多個線程向一個專用的寫程序線程提供信息/數據,如@FlorianSchaetz建議的那樣,該線程對您要寫入的文件具有獨占訪問權。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.