如果我有一個踏板,它計數至1000,並打印出結果,像這樣:無意的線程同步時寫入文件
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i=0;i<1000;i++){
System.out.println(i+" ");
}
}
}
而在main
我做這樣的事情:
new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();
的結果混亂起來,因爲我沒有同步。
但是,如果我的線程的樣子:
public class MyRunnable implements Runnable{
Writer w;
MyRunnable(Writer w){
this.w=w;
}
@Override
public void run() {
for (int i=0;i<1000;i++){
try{
w.write(String.valueOf(i));
w.write (" ") ;
}//&catch the exception
}
}
}
和我main
我有這樣的:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Thread.txt"), "utf-8"))) {
Thread t1 =new Thread(new MyRunnable(writer));
Thread t2 =new Thread(new MyRunnable(writer));
t1.start();
t2.start();
t1.join();
t2.join();
} //catch the exception,etc.
結果看起來正常:線程不知何故同步。我想這是因爲我通過writer
作爲參數,但有人可以更好地解釋它嗎?出於好奇,有沒有辦法解決它?
編輯:我的歉意,似乎我匆匆太多了。我試圖簡化MyThread並刪除了太多的代碼。但我只是意識到我描述的情況只會發生,如果我嘗試打開並在run()方法中讀取文件。所以運行其實看起來像這樣:
public void run() {
try {
Scanner scanner = new Scanner(f); //f is new File (filename)
while (scanner.hasNext())
{
String str = scanner.next();
if (str.equals("word")) //code counts "word" appearance
count++;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i=0;i<1000;i++){
try{
w.write(String.valueOf(i));
w.write (" ") ;
}//&catch the exception
} //continue by writing the count
我想這意味着問題實際上是在讀取文件?
硬盤一次只能寫一件東西。因此,如果兩個線程想同時寫入,其中一個線程將不得不等待另一個線程完成。 – litelite
@litelite它是一個'BufferedWriter',它不一定在每次寫入調用時寫入文件。 – matt
你是什麼意思結果將「看起來很正常」,如果我運行精確的測試結果混亂。 – matt