![](/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.