簡體   English   中英

為什么 InputStream read 方法會阻塞資源?

[英]Why does InputStream read method block the resource?

為什么 InputStream 的 read 方法在沒有什么可讀取的情況下會阻塞資源?

假設我在 RW 模式下打開了一個 RandomAccessFile,並且我使用文件描述符創建了 InputStream/OutputStream。

線程 1 正在嘗試從文件中讀取,而沒有可用的內容。 此時,如果線程 2 嘗試寫入文件,則會被阻塞。

為什么呢?

FileDescriptor是攜帶操作系統文件句柄的對象,這意味着它是攜帶文件指針的對象。

一次只有一個線程可以使用文件句柄/文件指針,因為FileDescriptor不支持多線程。 訪問已同步。

如果你想讓兩個線程獨立訪問文件,那么你需要兩個 FileDescriptor。

為了證明我的共享文件指針的觀點,如果您交替讀取FileInputStream和寫入FileOutputStream ,您認為會發生什么?

這是顯示發生了什么的代碼:

String fileName = "Test.txt";
Files.writeString(Paths.get(fileName), "abcdefghijklmnopqrstuvwxyz", StandardCharsets.US_ASCII);

try (RandomAccessFile raFile = new RandomAccessFile(fileName, "rw");
     FileInputStream in = new FileInputStream(raFile.getFD());
     FileOutputStream out = new FileOutputStream(raFile.getFD()) ) {

    byte[] buf = new byte[4];
    for (int i = 0; i < 3; i++) {
        int len = in.read(buf);
        System.out.println(new String(buf, 0, len, StandardCharsets.US_ASCII));

        out.write("1234".getBytes(StandardCharsets.US_ASCII));
    }
}

String s = Files.readString(Paths.get(fileName), StandardCharsets.US_ASCII);
System.out.println(s);

輸出

abcd
ijkl
qrst
abcd1234ijkl1234qrst1234yz

如您所見,讀取4個字節返回字節0-3並移動文件指針,因此寫入4個字節替換字節4-7,然后讀取4個字節返回字節8-11,寫入4個字節替換字節12-15 ,等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM