为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法防止 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 关注
  • 375 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号