1
我有兩個ExecutorService
實例:一個有4個線程,另一個有20個線程。我希望在點擊按鈕時,服務1停止並等待服務2結束。之後,服務1繼續運行。ExecutorService停止並等待另一個ExecutorService在Java中完成
我試着用wait
和notify
要做到這一點,但它不是按預期工作:
的ExecutorService 1:
public void readFile(JTextArea textArea) {
try {
File file = new File(this.fm.fullPath);
if (!file.exists()) {
return;
}
BufferedReader br = new BufferedReader(new FileReader(this.fm.fullPath));
ExecutorService executor = Executors.newFixedThreadPool(main.TOTALSTRINGS);
String line = br.readLine();
int i=1;
while (line != null) {
powThread t = new powThread("Thread" + (i+1), line, textArea);
executor.execute(t);
line = br.readLine();
i++;
}
executor.shutdown();
Thread t = new Thread() {
public void run() {
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
br.close();
} catch (Exception e) {
}
}
};
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
ExecutorService2:
public void generateNumStrings(JTextArea textArea) {
StringGenerator sg = new StringGenerator();
int[] dynamicThreads = main.calcThreadsTotal();
int totalThreads = dynamicThreads.length;
ExecutorService executor = Executors.newFixedThreadPool(totalThreads);
for(int i=0; i<totalThreads; i++) {
generateThread t = new generateThread("Thread" + (i+1), sg, dynamicThreads[i], this.fm);
executor.execute(t);
}
executor.shutdown();
Thread t = new Thread() {
public void run() {
try {
textArea.setText("");
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
textArea.append("File write successfully!");
} catch (InterruptedException e) {
}
}
};
t.start();
}
尼斯和有趣。 –