简体   繁体   English

只允许访问一个对象来读取文件并进行编写

[英]giving access to only one object to read a file and write it

I would like to know if multiple threads try to access a single txt file, how to restrict it? 我想知道多个线程是否尝试访问单个txt文件,如何限制它? If thread A tries to access the file till it completes the reading and writing part, other threads must wait. 如果线程A尝试访问文件直到它完成读写部分,则其他线程必须等待。 Here is what I tried. 这是我试过的。

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);
    }
}

An interesting way to do it would be to intern the string value of the file's FQN, and then synchronize on it. 一个有趣的方法是实现文件FQN的字符串值,然后在其上进行同步。 The more 'traditional' way is to use the FileChannel object and lock on it, with other processes simply waiting on the lock, to take their turns. 更“传统”的方式是使用FileChannel对象并对其进行锁定,其他进程只需等待锁定即可轮流使用。

Caveat : None of these solutions will solve contention between JVM's, or contention between a JVM and other external programs. 警告:这些解决方案都不能解决JVM之间的争用或JVM与其他外部程序之间的争用。

You can use a ReentrantReadWriteLock . 您可以使用ReentrantReadWriteLock

ReadWriteLock lock = new ReentrantReadWriteLock();

...

lock.readLock().lock();
try {
  //do reading stuff in here
} finally {
   lock.readLock().unlock();
}

...

lock.writeLock().lock();
try {
  //do writing stuff in here
} finally {
  lock.writeLock().unlock();
}

Or, for something simpler, you could synchronize on the interned (interning ensures that the String object is shared) String object that represents that File 's full path name: 或者,更简单的东西,你可以在实习(实习确保在同步String对象共享) String ,表示对象File的全路径名:

synchronized(file.getAbsolutePath().intern()) {
   //do operations on that file here
}

The ReadWriteLock approach will have better performance as Thread s will be allowed to read the file at the same time while manually synchronizing does not allow this. ReadWriteLock方法将具有更好的性能,因为允许Thread同时读取文件,而手动同步不允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM