gpt4 book ai didi

java - 等待回调而不暂停调用线程。我这样做对吗?

转载 作者:行者123 更新时间:2023-12-01 15:12:23 25 4
gpt4 key购买 nike

    public class Threadz implements Callable<String>{
private boolean flag = false;

@Override
public String call() throws Exception {
// TODO Auto-generated method stub
for(int i = 0; i < 3; i++){
Thread.sleep(2000);
}
flag = true;
return "Done";
}

public boolean isDone(){
return flag;
}
}

public class MyMain {
public static void main(String[] args) {
ExecutorService exe = Executors.newSingleThreadExecutor();
Threadz threadz = new Threadz();
Callable<String> cthread = threadz;
Future<String> fut = exe.submit(cthread);

while(true){
try {
if(!threadz.isDone())
System.out.println("Do something while waiting...");
else{
System.out.println(fut.get());
System.out.print("Do something with the result...");
break;
}
Thread.sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

我使用上述代码的目标是生成一个将返回结果的线程,但在等待结果时不应暂停调用线程。这确实有效,但我这样做正确吗?有没有正确的方法来做到这一点?另外,可调用线程在返回结果后是否会自动死亡(释放资源和内存)?

谢谢。

最佳答案

String callbackReturn = threadz.get();

如有必要,它会等待计算完成,然后检索其结果。

        ExecutorService exe = Executors.newSingleThreadExecutor();
Threadz threadz = new Threadz();
Callable<String> cthread = threadz;
Future<String> fut = exe.submit(cthread);
String callbackReturn = threadz.get();

当前线程将在这里等待。如果您不想暂停它,则在其他线程中处理它。

关于java - 等待回调而不暂停调用线程。我这样做对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12153828/

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