同一个文件可以同时被一个线程读另一个线程写吗?
如果有一个线程正在读文件,这时又有另个一个线程想来写这个文件 会报错吗?
答案是不会。
请运行以下的代码 就知道了
[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]
好像 可以吧
本文提供java多线程分别定时读写同一个文件的样例,其中两个线程,一个每分钟写入当前时间到指定文件,另一个线程读出每分钟新写的内容。
使用简单的Thread.sleep技术实现定时
package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Date;
/**
如果真的要求严格,应该用Timer继续比较精确的控制。
package test.thread;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
写加锁 读不加锁的
多个线程同时写都是可以的,你去看看java.nio.channels.FileChannel
亲,这个问题google大把答案还有现成的代码哦。亲!
同时读是没有任何问题的,直接读就可以了
至于同时写,因为有锁,不过要实现也是可以的
我的大体思想是这样的:比如有A和B两个线程,首先A把0-100的字节写进去,B开始读101-200的字节并存入一个缓存中,然后A退出开始读201-300之间的字节,B将缓存写入,如此循环就可以实现多线程读写了
本人的一点愚见,希望能帮到你
nio 就是非阻塞,读从来都没有加锁的啊