亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法防止 ClosedByInterruptException?

有沒有辦法防止 ClosedByInterruptException?

一只甜甜圈 2021-09-12 16:16:10
在下面的示例中,我有一個文件被兩個線程使用(在實際示例中,我可以擁有任意數量的線程)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 僅僅因為使用它的一個線程被中斷而被關閉?
查看完整描述

3 回答

  • 3 回答
  • 0 關注
  • 392 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號