Java InputStream在Thread中关闭

时间:2015-04-17 21:13:32

标签: java multithreading io

我正在尝试从线程中的InputStream中读取。

Thread应该运行的类看起来像这样

static private class Runner implements Runnable {

    private InputStream fis;
    private OutputStream fos;

    public Runner(InputStream fis, OutputStream fos) throws IOException {

        int blu = fis.available();

        System.out.println(blu);

        this.fis = fis;

        int bla = this.fis.available();

        System.out.println(bla);
        this.fos = fos;
    }

    @Override
    public void run() {

        try {
            int bla = fis.available();

            System.out.println(bla);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(fis);
        System.out.println(fos);

    }

}

Thread就像这样创建

final Runnable runnable = new Runner(fis, fos);
final Thread thread = new Thread(runnable);
thread.start();

在Thread上运行run方法。但是一旦执行它我就会得到错误

java.nio.channels.ClosedChannelException

我调试了它,并且InputStream设置为关闭。

为什么在Thread中关闭InputStream?有没有我应该使用的替代方案?

编辑:

我忘了提到它们是在这样的试块中打开的,之后主要功能就结束了。

try (InputStream fis = Files.newInputStream(sourcePath)) {
        try (OutputStream fos = Files.newOutputStream(sinkPath)) {

            final Runnable runnable = new Runner(fis, fos);
            final Thread thread = new Thread(runnable);
            thread.start();
        }

    }

2 个答案:

答案 0 :(得分:4)

当块退出时,那些try-with-resources块将关闭它们各自的流。当您只计划使用块内的流时,这很好。但是因为你想在块结束后继续在另一个线程中使用流,所以去除块。

InputStream  fis = Files.newInputStream (sourcePath);
OutputStream fos = Files.newOutputStream(sinkPath);

final Runnable runnable = new Runner(fis, fos);
final Thread   thread   = new Thread(runnable);
thread.start();

答案 1 :(得分:3)

因为你在Try中有它,所以当线程离开try块时它会关闭。 Thread.start()不会挂起,因此它会自动关闭。

这样做:

InputStream  fis = Files.newInputStream (sourcePath);
OutputStream fos = Files.newOutputStream(sinkPath);

final Runnable runnable = new Runner(fis, fos);
final Thread thread = new Thread(runnable);
thread.start();

在你的主题中:

   public void run() {

        try {
            int bla = fis.available();

            System.out.println(bla);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            System.out.println(fis);
            System.out.println(fos);
            fis.close();
            fis.close();
        }
    }