猿问

有没有办法防止 ClosedByInterruptException?

在下面的示例中,我有一个文件被两个线程使用(在实际示例中,我可以拥有任意数量的线程)


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 仅仅因为使用它的一个线程被中断而被关闭?


一只甜甜圈
浏览 376回答 3
3回答
随时随地看视频慕课网APP

相关分类

Java
我要回答