2013-04-24 3 views
-1

프로그램을 읽고 쓰기를 원합니다. 한 번에 하나의 작업 (읽기 또는 쓰기)을 수행하고 싶습니다. 파일을 읽는 중이면 읽기 작업이 끝날 때까지 쓰기 요청이 대기합니다. 파일을 쓰고 쓰기 요청이 끝날 때까지 기다리십시오.스레드를 사용하여 파일을 읽거나 쓰는 중

+0

그리고 질문을 뭐야? –

답변

0

예를 들어, 완전히 동기화 읽기와 쓰기를 할 수있는 클래스를 만들고합니다

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!"); 
+0

이 답변을 좋아하는 경우 투표하실 수 있습니다.) – Dima

0

뮤텍스를 사용해야합니다. 이것은 한 번에 하나의 쓰레드 만 ressource를 사용할 수 있도록하는 구조입니다. ReentrantLock을 둘러보십시오.

관련 문제