Java 使用线程读取或写入文件

Java 使用线程读取或写入文件,java,synchronization,thread-safety,Java,Synchronization,Thread Safety,我想要读写文件的程序。我想要一次执行任何一个操作(读或写)。如果我正在读文件,写请求将等待读操作完成。如果我正在写文件,那么读请求将等待读操作完成。您必须使用互斥锁。这种结构一次只允许一个线程使用ressource。查看ReentrantLock。创建一个类来执行读写操作,并使其完全同步,例如: public class MyFileManager{ private static MyFileManager instance; public static synchronized My

我想要读写文件的程序。我想要一次执行任何一个操作(读或写)。如果我正在读文件,写请求将等待读操作完成。如果我正在写文件,那么读请求将等待读操作完成。您必须使用互斥锁。这种结构一次只允许一个线程使用ressource。查看ReentrantLock。

创建一个类来执行读写操作,并使其完全同步,例如:

public class MyFileManager{
  private static MyFileManager instance;

  public static synchronized MyFileManager getInstance(){ // to use as singelton
    if(instance==null){
      instance=new MyFileManager();
    }
    return instance;
  }

  private MyFileManager(){} // to avoid creation of new instances


 public synchronized String read(File f){
   //Do Something
 }

 public synchronized void write(File f, String s){
   //Do Something
 }

}
现在,当你想读或写的时候,就这么做吧

String s=MyFileManager.getInstance.read(myfile);
MyFileManager.getInstance.write(myfile,"hello world!");

你知道如果你喜欢这个答案,你可以投赞成票;)