I want thread 1 to write in a text file and then thread 2 write another thing, but thread 2 will always overwrite what thread 1 wrote
how can i prevent this using Synchronization(if possible) ?
MultiThreadMain.java
:
public class MultiThreadMain {
public static void main(String[] args) throws InterruptedException {
ReadFile thread1 = new ReadFile();
ReadFile thread2 = new ReadFile();
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
ReadFile.java
:
public class ReadFile extends Thread {
synchronized void ReadTxtFile() throws IOException {
FileWriter write = new FileWriter("filelocation");
write.write("hello");
write.close();
}
@Override
public void run() {
try {
ReadTxtFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}