我Java
Thread
正在使用一个异步将某些文件上传到服务器的协议。完成上传后,我需要线程返回一些值。因此,如本示例中所述,我创建了另一个方法,该方法返回一些值并从主类访问该方法。根据我的要求,我必须上载多个文件,以便该线程第二次运行时挂起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接口,如下所示。它解决了我的问题。
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;
}
}
}
从主类执行可调用:
for (int i=0; i<fileList.length;i++) {
Upload up = new Upload();
FutureTask<Integer> future = new FutureTask(up);
future.run();
int result = future.get();
}
我从这里开始跟随例子
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句