在下面的示例中,我有一個文件被兩個線程使用(在實際示例中,我可以擁有任意數量的線程)import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class A { static volatile boolean running = true; public static void main(String[] args) throws IOException, InterruptedException { String name = "delete.me"; new File(name).deleteOnExit(); RandomAccessFile raf = new RandomAccessFile(name, "rw"); FileChannel fc = raf.getChannel(); Thread monitor = new Thread(() -> { try { while (running) { System.out.println(name + " is " + (fc.size() >> 10) + " KB"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); Thread.currentThread().interrupt(); } } } catch (IOException e) { System.err.println("Monitor thread died"); e.printStackTrace(); } }); monitor.setDaemon(true); monitor.start(); Thread writer = new Thread(() -> { ByteBuffer bb = ByteBuffer.allocateDirect(32); try { while (running) { bb.position(0).limit(32); fc.write(bb); try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println("Interrupted"); Thread.currentThread().interrupt(); } } } catch (IOException e) { System.err.println("Writer thread died"); e.printStackTrace(); } });而不是為每個線程創建一個 RandomAccessFile 和一個內存映射,我有一個文件和一個在線程之間共享的內存映射,但是有一個問題,如果任何線程被中斷,資源就會關閉。有什么辦法可以防止 FileChannel 僅僅因為使用它的一個線程被中斷而被關閉?
添加回答
舉報
0/150
提交
取消