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