I have two Threads and each Thread should write its name and an increasing number into a file - but it doesn't work.
If i use the System.out.println()
method the threads are working perfectly only the writing into the file does fail. Any idea why?
This is how my Threads look like:
package ThreadTest;
import java.io.*;
public class Thread1 implements Runnable {
public void run() {
int x = 0;
while (true) {
try {
BufferedWriter p1 = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt"));
x++;
p1.write("Thread11: " + x);
Thread.sleep(500);
p1.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
The main class looks like this:
package ThreadTest;
public class ThreadTestTest {
public static void main(String args[]) {
try {
Thread1 t11 = new Thread1();
Thread t1 = new Thread(t11);
Thread2 t22 = new Thread2();
Thread t2 = new Thread(t22);
t2.start();
t1.start();
t1. join();
t2. join();
} catch (Exception e) {
e.getMessage();
}
}
}
关闭文件后,立即立即将其打开,从而将其截断为零长度。
As Henry already pointed out, you essentially need to make your BufferedWriter shared between the threads so you don't constantly overwrite the file again.
The following will do:
public class ThreadTest {
public static void main(String[] args) {
class ThreadSafeBufferedWriter extends BufferedWriter {
public ThreadSafeBufferedWriter(Writer out) {
super(out);
}
@Override
public synchronized void write(String str) throws IOException {
super.write(str);
}
}
try (BufferedWriter p1 = new ThreadSafeBufferedWriter(new FileWriter("/tmp/out.txt"))) {
Thread t1 = new Thread(new Payload("Thread1", p1));
Thread t2 = new Thread(new Payload("Thread2", p1));
t2.start();
t1.start();
t2.join();
t1.join();
}
catch (Exception e) {
// do something smart
}
}
}
The actual payload comes in a Runnable which goes here:
class Payload implements Runnable {
private String name;
private Writer p1;
public Payload(String _name, Writer _p1) {
this.name = _name;
this.p1 = _p1;
}
@Override
public void run() {
int x = 0;
while (x < 10) { // you have to make sure these threads actually die at some point
try {
x++;
this.p1.write(this.name + ": " + x + "\n");
Thread.sleep(500);
} catch (Exception e) {
// do something smart
}
}
}
}
Thanks guys :)!
I just added a true to the file location:
PrintWriter p2 = new PrintWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt",true));
And now java appends the text instead of overwriting the old one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.