2012-03-25 4 views
0

여러 스레드가 단일 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); 
    } 
} 
+1

질문에 중요하지 않지만,'main'에서 쓰레드를 만들고 (시작하는 것), 당신은 아무것도하지 않아야합니다. - 당신은'readFromFile'에 새로운 쓰레드를 시작하고, 전달 된 쓰레드에 대한 참조를 바꿉니다. 매개 변수. 불필요한 것 같습니다. – Attila

답변

1

재미있는 방법은 파일의 FQN의 문자열 값을 인턴에게주고 동기화하는 것입니다. 더 전통적인 '길'은 FileChannel 개체를 사용하고 잠금 장치를 기다리는 다른 프로세스와 함께 개체를 잠그는 것입니다.

경고 : 이러한 솔루션은 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

나는 어느 정도 이해했다. 아직 시험 중이 야. Jeffrey에게 감사드립니다. – sahana