多线程之实现Callable接口
/**
*1、实现Callable接口,需要返回值类型
- 2、重写call方法,需要抛出异常
- 3、创建目标对象
- 4、创建执行服务:
- 5、提交执行:
- 6、获取结果:
- 7、关闭服务:
- */
package com.chenheng.demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/**
*1、实现Callable接口,需要返回值类型
* 2、重写call方法,需要抛出异常
* 3、创建目标对象
* 4、创建执行服务:
* 5、提交执行:
* 6、获取结果:
* 7、关闭服务:
* */
public class TestThreadCallable implements Callable<Boolean> {
private String url;
private String name;
public TestThreadCallable(String url,String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("已经下载"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestThreadCallable t1 = new TestThreadCallable("http://www.njit.edu.cn//__local/E/D4/BC/A7A34353A191AFD49117C07580B_ACC3D268_7CB41.jpg", "1.jpg");
TestThreadCallable t2 = new TestThreadCallable("http://www.njit.edu.cn/images/19/07/04/1c9h9beu9o/g1.jpg", "2.jpg");
TestThreadCallable t3 = new TestThreadCallable("http://www.njit.edu.cn/images/buwangcx.png", "3.jpg");
/**
*创建执行服务:
*/
ExecutorService executorService = Executors.newFixedThreadPool(3);
/**
* 提交执行:
*/
Future<Boolean> submit1 = executorService.submit(t1);
Future<Boolean> submit2 = executorService.submit(t2);
Future<Boolean> submit3 = executorService.submit(t3);
/**
* 获取结果:
*/
Boolean flag = submit1.get();
Boolean flag2 = submit2.get();
Boolean flag3 = submit3.get();
System.out.println(flag);
System.out.println(flag2);
System.out.println(flag3);
/**
*
* 关闭服务:
*/
executorService.shutdown();
}
}
/**
* 下载器
* */
class WebDownloader{
/**
* 下载方法
* */
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法下载出现问题!");
}
}
}