同一个文件可以同时被一个线程读另一个线程写吗?
8条回答 默认 最新
- goodscript_cn 2013-03-08 02: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]本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报