我有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);
}
答案 0 :(得分:1)
我已经使用回调实现了Future接口,如下所示。它解决了我的问题。
Callable
实施:
public class Upload implements Callable<Integer> {
public Upload() {
}
@Override
public Integer call() {
try {
//Upload happens here. after completing returns value as required.
return 0;
}
}
}
从主类执行callable:
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
中的示例进行操作