我使用ExecutorService創建了兩個獨立的線程。現在我只想讓一個線程將數據寫入一個文件,另一個線程在從將數據寫入文件的線程獲取通知之後將讀取它,但輸出沒有顯示任何內容,那麼如何才能實現我的目標。如何做兩個獨立的線程等待和通知?
My code is:
package threadingexamples;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadingExamples {
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(new ForLoo1());
es.submit(new ForLoop2());
es.shutdown();
es.awaitTermination(1, TimeUnit.DAYS);
System.exit(0);
}
}
class ForLoo1 implements Callable<Object> {
@Override
public Object call() throws Exception {
System.out.println("I am writing content into file....");
String s = "This is the content to write into a file";
File file = new File("/home/f.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s);
bw.close();
System.out.println("Now you can read content from files...");
notify();
return null;
}
}
class ForLoop2 implements Callable<Object> {
@Override
public Object call() throws Exception {
wait();
System.out.println("Okay i am now going to read content of files...");
BufferedReader br = new BufferedReader(new FileReader("f.txt"));
String str;
while ((str = br.readLine()) != null) {
str = str + "";
}
System.out.println("I am done with reading.....");
System.out.println(str);
return null;
}
}
線程1調用ForLoop1實例的notify(),而線程2調用ForLoop2實例的wait()。這是行不通的。而且,你在等待時沒有使用while循環。不要使用等待和通知,這是太低級。使用更高級的,更容易使用的抽象,如CountDownLatch。 –
你的線程之間沒有同步。在確認有需要等待的時候,你不能叫'等待'。如果'call'運行完成,那麼你將等待已經發生的事情,這將意味着永遠等待。 –
查看[Semaphore](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html)或[CountDownLatch](https://docs.oracle。 com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) –