java的callable接口的基本实现
package Thread;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class DownloadPicture {
public void download(String url,String name) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(url), new File(name));
}
}
package Thread;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDownload implements Callable{
private String url;
private String name;
public CallableDownload(String url, String name) {
this.url = url;
this.name = name;
}
public Boolean call() {
DownloadPicture d = new DownloadPicture();
try {
d.download(url, name);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
CallableDownload c1 = new CallableDownload("http://www.pptbz.com/uploadimg//pptpic/201306/2013062320262198.jpg","t1.jpg");
CallableDownload c2 = new CallableDownload("http://www.pptbz.com/uploadimg//pptpic/201306/2013062320262198.jpg","t2.jpg");
CallableDownload c3 = new CallableDownload("http://www.pptbz.com/uploadimg//pptpic/201306/2013062320262198.jpg","t3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> result1 = ser.submit(c1);
Future<Boolean> result2 = ser.submit(c2);
Future<Boolean> result3 = ser.submit(c3);
//获取结果
boolean b1 = result1.get();
boolean b2 = result1.get();
boolean b3 = result1.get();
//关闭服务
ser.shutdownNow();
}
}