文章目录
说明
线程A和线程B通过文件的方式进行通信,A往文件写入数据,B从文件中读取数据。
代码
private int i = 0;
/**
* 通过文件方式进行通信
*/
public void methodOfFile() {
new Thread(() -> {
while (true) {
try {
Thread.sleep(3000);
Files.write(Paths.get("method_of_file.txt"), String.valueOf(i++).getBytes());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(()-> {
while (true) {
byte[] bytes = new byte[0];
try {
Thread.sleep(4000);
bytes = Files.readAllBytes(Paths.get("method_of_file.txt"));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
System.out.println(new String(bytes));
}
}).start();
}