import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class FlushTest { private static final String FILE_PATH = System.getProperty("user.home") + "/tmp/flush_test.txt"; public static void main(String[] args) { System.out.println("FILE_PATH:" + FILE_PATH); for (int i=1; i<=2; i++) { final int index = i; new Thread(() -> { try( FileOutputStream fos = new FileOutputStream(new File(FILE_PATH)); OutputStreamWriter osw = new OutputStreamWriter(fos); ) { if (index == 1) { osw.write("11111111\n"); osw.write("11111111\n"); osw.write("11111111\n"); }else { osw.write("2\n"); osw.write("2\n"); osw.write("2\n"); osw.write("2\n"); osw.write("2\n"); osw.write("2\n"); } System.out.println(index + ":" + System.currentTimeMillis()); osw.flush(); } catch (Exception e) { } }).start(); } try { Thread.sleep(1000); /* 多次运行后,会有这三种情况,而且第三种情况的1打印有点特殊 [11111111, 11111111, 11111111] [2, 2, 2, 2, 2, 2] [2, 2, 2, 2, 2, 2, 11111, 11111111] */ System.out.println(read()); } catch (Exception e) { e.printStackTrace(); } deleteFile(); } private static List<String> read() { List<String> list = new ArrayList<>(); try (FileReader fr = new FileReader(new File(FILE_PATH)); BufferedReader br = new BufferedReader(fr)) { String line; while ((line = br.readLine()) != null) { list.add(line); } } catch (Exception e) { e.printStackTrace(); } return list; } private static void deleteFile() { new File(FILE_PATH).delete(); } }
如上面的java所示,运行多次后,read()方法的输出会有三种情况
[11111111, 11111111, 11111111]
[2, 2, 2, 2, 2, 2]
[2, 2, 2, 2, 2, 2, 11111, 11111111]
第三种输出就有点奇怪了,特别是只输出“5个1”那一段,不知谁能来解答一下!
几个因素
1 主线程睡眠1s,时间可能不够主程序就结束了
2 2个线程共享index,此时存在共享变量的问题,而且你这个变量在闭包中
3 FileOutputStream这个流也被线程共享了,存在互相写的问题
1、1s太短可以设置长一点,结果一样
2、index线程不共享
3、FileOutputStream是共享的,但为啥导致了输出5个1
居然没有一个满意的答案
final int index = i;循环了二次创建了二个线程,第三种情况会打印2,1因为线程不是同步的,osw对象也没关闭所以二条线程都在跑