gpt4 book ai didi

java - ExecutorService 停止并等待另一个 ExecutorService 在 Java 中完成

转载 作者:行者123 更新时间:2023-11-30 03:01:33 31 4
gpt4 key购买 nike

我有两个 ExecutorService 实例:一个有 4 个线程,另一个有 20 个线程。我希望单击按钮后,服务 1 就会停止并等待服务 2 结束。之后,服务1继续运行。

我尝试使用 waitnotify 来执行此操作,但它没有按预期工作:

执行服务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();
}

最佳答案

您可以使用AtomicReference在第一个 ExecutorService 中包装第二个 ExecutorService;如果第二个 ExecutorService 尚未实例化,则返回 null,然后 awaitTermination 如果引用非空。我假设 readFilegenerateNumStrings 位于同一个类中,如果不是,那么您需要找到某种方法来制作 AtomicReference generateNumStrings

可见
private final AtomicReference<ExecutorService> ref = new AtomicReference<>(null);

private void awaitTermination() throws InterruptedException {
ExecutorService executor = ref.get();
if(executor != null) {
executor.awaitTermination(1, TimeUnit.DAYS);
}
}

public void readFile(JTextArea textArea) {
...
while (line != null) {
awaitTermination();
powThread t = new powThread("Thread" + (i+1), line, textArea);
executor.execute(t);
line = br.readLine();
i++;
}
...
}

public void generateNumStrings(JTextArea textArea) {
...
ExecutorService executor = Executors.newFixedThreadPool(totalThreads);
ref.set(executor);
...
}

关于java - ExecutorService 停止并等待另一个 ExecutorService 在 Java 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35815463/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com