首先用Runnable实现下载三个线程并发通过URL下载图片
public class DownloadThread implements Runnable{
private String path;
private String name;
public DownloadThread(String name, String path) {
this.path = path;
this.name = name;
}
@Override
public void run() {
WbdDownlaoder wd=new WbdDownlaoder();
wd.download(path,name);
}
public static void main(String[] args) {
DownloadThread dlt=new DownloadThread("1.jpg","http://a3.att.hudong.com/68/61/300000839764127060614318218.jpg");
DownloadThread dlt2=new DownloadThread("2.jpg","http://a3.att.hudong.com/40/61/300000839764127060614527184.jpg");
DownloadThread dlt3=new DownloadThread("3.jpg","http://a2.att.hudong.com/71/61/300000839764127060614885914.jpg");
new Thread(dlt).start();
new Thread(dlt2).start();
new Thread(dlt3).start();
}
}
class WbdDownlaoder{
public void download(String path,String name){
try {
FileUtils.copyURLToFile(new URL(path),new File(name));
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.println("不合法的url");
} catch (IOException e) {
e.printStackTrace();
System.out.println("下载失败");
}
}
}
然后是通过Callable接口:
Callable接口接口使用步骤:
创建目标对象
Class C implements Callable
C c=new C();
ExecutorService ser=Executors.newFixedThreadPool(n);//创建线程池,有几个线程则大小n就为几个
Future result1=ser.submit(线程1) //提交执行
boolean r1=result.get();//获取结果
ser.shutdownNow();//关闭服务
public class DownloadThread implements Callable<Boolean> {
//设定返回值泛型,默认是Objects,这里使用Boolean
private String path;
private String name;
public DownloadThread(String name, String path) {
this.path = path;
this.name = name;
}
@Override
public Boolean call() throws Exception{// //类实现Callable的好处是重写的call方法可以提交异常!
WbdDownlaoder wd=new WbdDownlaoder();
wd.download(path,name);
return true;
}
public static void main(String[] args) {
DownloadThread dlt1=new DownloadThread("1.jpg","http://a3.att.hudong.com/68/61/300000839764127060614318218.jpg");
DownloadThread dlt2=new DownloadThread("2.jpg","http://a3.att.hudong.com/40/61/300000839764127060614527184.jpg");
DownloadThread dlt3=new DownloadThread("3.jpg","http://a2.att.hudong.com/71/61/300000839764127060614885914.jpg");
ExecutorService ser= Executors.newFixedThreadPool(3);
Future<Boolean> result1=ser.submit(dlt1);
Future<Boolean> result2=ser.submit(dlt2);
Future<Boolean> result3=ser.submit(dlt3);
ser.shutdownNow();
}
}
还可以获得线程1执行的结果
boolean r1=result1.get();