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

时间:2012-03-25 18:36:54

标签: 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);
    }
}

2 个答案:

答案 0 :(得分:1)

一种有趣的方法是实习文件FQN的字符串值,然后对其进行同步。更“传统”的方式是使用FileChannel对象并锁定它,其他进程只是等待锁定,轮流使用。

警告:这些解决方案都不能解决JVM之间的争用,或JVM与其他外部程序之间的争用。

答案 1 :(得分:1)

您可以使用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();
}

或者,对于更简单的事情,您可以在interned上进行同步(实习确保共享String对象)String表示File的完整路径名的对象:< / p>

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

ReadWriteLock方法将具有更好的性能,因为Thread将允许同时读取文件,而手动同步不允许这样做。