我運行五個線程來生成隨機字符串數據,然后僅寫入一個輸出流。程序完成后,一些數據丟失了。我簡化了我的代碼。new Thread(() -> { stream.write(RANDOM_STRING + "\n)).start();class Stream { String buffer = ""; Stream() { new Thread(() -> { BufferedOutputStream bs = new BufferedOutputStream(new FileOutputStream("PATH"); bs.wrtie(buffer.getBytes()); // point 1 buffer = "" // point 2 bs.close(); }).start(); } public void write(String input) { buffer += input; }}我認為數據丟失的原因在第1點和第2點之間。我想如果我使用索引數據結構來檢查消耗了哪些數據,就可以解決。但有沒有更好的方法來解決這個問題呢?請幫我。謝謝。
多線程只寫一個輸出流并且數據丟失
幕布斯6054654
2023-08-16 15:51:38