java - 仅允许访问一个对象来读取和写入文件

标签 java multithreading singleton synchronized

我想知道如果多个线程尝试访问单个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/

相关文章:

ruby 线程,杀死与终止与退出

swift - 在 Swift 中使用 dispatch_once 单例模型

python - python中的对象破坏

javascript - 在Javascript单例中用数组成员初始化对象成员的属性

java - 在Where子句中插入字符串变量

java - 并行程序 Java 中的埃拉托斯特尼筛法

c# - Thread.Sleep 的替代品

java - 我的java猜数程序错误

java - 在HQL中使用Hibernate for Java获取异常行为绑定(bind)parameterList时

java.net.SocketException : Broken pipe smpp. 逻辑库