我想知道如果多个线程尝试访问单个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);
}
}
最佳答案
一种有趣的方法是实习文件 FQN 的字符串值,然后对其进行同步。更“传统”的方法是使用 FileChannel
对象并锁定它,其他进程只需等待锁定即可轮流执行。
警告:这些解决方案都无法解决 JVM 之间的争用,或 JVM 与其他外部程序之间的争用。
关于java - 仅允许访问一个对象来读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9862869/