-
-
Save optor666/ef1e8d58fdbf8f72ad32f22574fdaaa9 to your computer and use it in GitHub Desktop.
Multi Thread Write Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileWriter; | |
import java.io.IOException; | |
public class FileWriterExample2 { | |
public static void main(String[] args) throws IOException, InterruptedException { | |
FileWriter fw = new FileWriter("/tmp/test", true); | |
FileWriter fw2 = new FileWriter("/tmp/test", true); | |
char[] chars = new char[1024 * 1024 * 4]; | |
for (int i = 0; i < 4 * 1024 * 1024; i++) { | |
chars[i] = (char) 'a'; | |
} | |
char[] chars1 = new char[4 * 1024 * 1024]; | |
for (int i = 0; i < 4 * 1024 * 1024; i++) { | |
chars1[i] = (char) 'b'; | |
} | |
for (int i = 0; i < 10; i++) { | |
Thread thread1 = new Thread(() -> { | |
try { | |
fw.write(chars); | |
fw.write("hello\n"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
Thread thread2 = new Thread(() -> { | |
try { | |
fw.write(chars1); | |
fw.write("world\n"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
thread1.join(); | |
thread2.join(); | |
thread1.start(); | |
thread2.start(); | |
} | |
fw.close(); | |
fw2.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment