造成java.io.IOException: Stream Closed异常的代码

两个线程同时持有一个inputstream,其中一个线程关闭了stream,另一个正在读取时,产生这个异常。

代码如下:

package com.example;

import java.io.FileInputStream;
import java.io.IOException;

public class MultiThread {
    
    public static void main(String[] args) throws Exception
    {
        final FileInputStream fis = new FileInputStream("d:/test/test.txt");
        
        Thread th1 = new Thread(new Runnable() {
            
            @Override
            public void run() {
                try {
                    int content = fis.read();
                    while(content != -1)
                    {
                        System.out.println(content);
                        content = fis.read();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
            }
        });
        
        Thread th2 = new Thread( new Runnable() {
            
            @Override
            public void run() {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        
        th2.run();
        th1.run();
    }

}

 

posted @ 2016-03-08 13:33  ThinkOfLife  阅读(4202)  评论(0编辑  收藏  举报