【发布时间】:2012-03-25 18:36:54
【问题描述】:
我想知道如果多个线程尝试访问单个txt文件,如何限制它? 如果线程 A 尝试访问文件直到它完成读写部分,其他线程必须等待。这是我尝试过的。
package singleton;
/**
*
* @author Admin
*/
import java.io.*;
class ReadFileUsingThread
{
public synchronized void readFromFile(final String f, Thread thread) {
Runnable readRun = new Runnable() {
public void run() {
FileInputStream in=null;
FileOutputStream out=null;
String text = null;
try{
Thread.sleep(5000);
File inputFile = new File(f);
in = new FileInputStream(inputFile);
byte bt[] = new byte[(int)inputFile.length()];
in.read(bt);
text = new String(bt);
//String file_name = "E:/sumi.txt";
//File file = new File(file_name);
// FileWriter fstream = new FileWriter("E:/sumi.txt");
out = new FileOutputStream("E:/sumi.txt");
out.write(bt);
System.out.println(text);
} catch(Exception ex) {
}
}
};
thread = new Thread(readRun);
thread.start();
}
public static void main(String[] args)
{
ReadFileUsingThread files=new ReadFileUsingThread();
Thread thread1=new Thread();
Thread thread2=new Thread();
Thread thread3=new Thread();
String f1="C:/Users/Admin/Documents/links.txt";//,f2="C:/employee.txt",f3="C:/hello.txt";
thread1.start();
files.readFromFile(f1,thread1);
thread2.start();
files.readFromFile(f1,thread2);
thread3.start();
files.readFromFile(f1,thread3);
}
}
【问题讨论】:
-
对这个问题并不重要,但您正在
main中创建(并启动)线程,而您不做任何事情 - 您正在readFromFile中启动新线程并替换参考到作为参数传递的线程。似乎没有必要。
标签: java multithreading singleton synchronized