2012-03-25 11 views
0

複数のスレッドが1つのtxtファイルにアクセスしようとしている場合は、どのように制限するのですか? スレッドAが読み書き部分を完了するまでファイルにアクセスしようとすると、他のスレッドは待機する必要があります。ここで私が試したことがあります。ファイルを読み込んで1つのオブジェクトだけにアクセスして書き込みを行う

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

質問には重要ではありませんが、あなたが何もしない 'main'のスレッドを作成(そして開始)しています - あなたは' readFromFile'で新しいスレッドを開始しています。パラメータ。不要です。 – Attila

答えて

1

興味深いのは、ファイルのFQNの文字列値をインターンにしてから同期させることです。より伝統的な方法は、FileChannelオブジェクトを使用し、ロックを待つだけの他のプロセスで、オブジェクトをロックすることです。

警告:これらの解決策のいずれも、JVMの競合、またはJVMと他の外部プログラムとの競合を解決するものではありません。

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

それとも、単純に何かのために、あなたは表し(インターンがStringオブジェクトが共有されていることを保証します)インターンStringオブジェクトで同期できることFileのフルパス名:

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

ReadWriteLockアプローチは、Threadが同時にファイルを読み取ることが許可されるため、手動同期では許可されないため、パフォーマンスが向上します。

+0

このコード部分をどこに追加すればよいか教えてください。 – sahana

+0

@sahana 'ReadWriteLock'アプローチをとっているなら、' lock'はファイルにアクセスしようとしている 'Thread'にアクセス可能でなければなりません。同期の方法をとっている場合は、すべての読み書き操作を囲む必要があります。 – Jeffrey

+0

私はある程度理解しました。まだ試してみる。ありがとう、ジェフリー。 – sahana

関連する問題