alanchenyan 2013-03-06 14:20
浏览 1010
已采纳

java多线程读写同一个文件

      同一个文件可以同时被一个线程读另一个线程写吗?

  • 写回答

8条回答 默认 最新

  • goodscript_cn 2013-03-08 10:35
    关注

    如果有一个线程正在读文件,这时又有另个一个线程想来写这个文件 会报错吗?
    答案是不会。
    请运行以下的代码 就知道了
    [code="java"]package org.sse.test;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

    public class IO {

    /**
     * @param args
     */
    public static void main(String[] args) {
        new IO().test();
    }
    
    private void test() {
        ReadThead rt = new ReadThead();
        Thread t1 = new Thread(rt, "ReadThead");
        WriteThead wt = new WriteThead();
        Thread t2 = new Thread(wt, "WriteThead");
        t1.start();
        t2.start();
    }
    
    protected class WriteThead implements Runnable {
    
        @Override
        public void run() {
            try {
                File f = new File("D:\\A.txt");
                FileOutputStream fos = new FileOutputStream(f);
                byte[] b = "hello".getBytes();
                while (true) {
                    fos.write(b);
                    fos.flush();
                    Thread.sleep(1000);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    
    protected class ReadThead implements Runnable {
    
        @Override
        public void run() {
            try {
                File f = new File("D:\\A.txt");
                FileInputStream fis = new FileInputStream(f);
                int readData;
                while (true) {
                    readData = fis.read();
                    if (readData == -1) {
                        Thread.sleep(1000);
                    } else {
                        System.out.println(readData);
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
    }
    

    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法