我有一个 Java
Thread
,用于将一些文件异步上传到服务器。我需要我的线程在完成上传后返回一些值。正如 this 中提到的例如,我创建了另一个方法,它返回一些值并从主类访问该方法。至于我的要求,我必须上传多个文件,因此如果线程第二次运行,它会卡在 t1.join() 上。所以我需要知道解决我的问题的最佳方法是什么。?
我的上传线程:
public class UploadThread extends Thread {
public UploadThread() {
}
@Override
public void run() {
try {
//Upload happens here
} catch (IOException ex) {
Logger.getLogger(UploadThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Method use to return upload status
public String status() {
//verify upload has completed
return "Upload successful";
}
}
从主类调用线程:
//Calling upload thread multiple times depends on no of files
for (int i = 0; i < fileList.length; i++) {
UploadThread t1 = new UploadThread();
t1.start();
t1.join();
String status = t1.status();
System.out.println(status);
}
最佳答案
我已经实现了带有回调的 Future 接口(interface),如下所示。它解决了我的问题。
可调用
实现:
public class Upload implements Callable<Integer> {
public Upload() {
}
@Override
public Integer call() {
try {
//Upload happens here. after completing returns value as required.
return 0;
}
}
}
从主类执行可调用:
for (int i=0; i<fileList.length;i++) {
Upload up = new Upload();
FutureTask<Integer> future = new FutureTask(up);
future.run();
int result = future.get();
}
我按照 here 中的示例进行操作
关于java - 线程完成执行后返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678556/