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