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