实现Callable接口

实现Callable接口

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
  5. 提交执行:Future result1 = ser.submit(t1);
  6. 获取结果:boolean r1 = result1.get()
  7. 关闭服务:ser.shutdownNow();
  • 使用Callable来改写图片下载项目

    //使用Callable来改写图片下载项目
    public class CallableTest implements Callable<Boolean> {
        private String url;   //网络地址
        private String name;  //文件名
    
        public CallableTest(String url,String name){
            this.url = url;
            this.name = name;
        }
    
        //下载图片的执行体
        @Override
        public Boolean call() {
            WebDownLoad webDownLoad = new WebDownLoad();
            webDownLoad.downLoad(url,name);
            System.out.println("文件名:"+name);
            return true;
        }
    
        //练习:Thread ,实现多线程下载图片
        public static void main(String[] args) throws Exception{
            CallableTest th1 = new CallableTest("https://img.yalayi.net/d/file/2020/07/24/b6c4ac6b58124d7ac70344ea4992ab5d.jpg","xg1.jpg");
            CallableTest th2 = new CallableTest("https://img.yalayi.net/d/file/2020/06/22/13c501bca19b48eb558b4147493330f4.jpg","xg2.jpg");
            CallableTest th3 = new CallableTest("https://img.yalayi.net/d/file/2020/06/22/f49a10d2884df025bba6ced8e50cfa2f.jpg","xg3.jpg");
            //下载次序每次都会不同
            //创建执行服务 开启线程池:3为线程池数量
            ExecutorService ser= Executors.newFixedThreadPool(3);
            //提交执行
            Future<Boolean> future1=ser.submit(th1);
            Future<Boolean> future2=ser.submit(th2);
            Future<Boolean> future3=ser.submit(th3);
            //获取结果
            boolean flag1= future1.get();
            boolean flag2= future2.get();
            boolean flag3= future2.get();
            System.out.println(flag1);
            System.out.println(flag2);
            System.out.println(flag3);
            //关闭服务
            ser.shutdownNow();
        }
    }
    
    class WebDownLoad{
        //下载方法
        public void downLoad(String url,String name){
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("IO异常,downLoad方法");
            }
        }
    }
    
posted @ 2021-04-25 09:29  saxon宋  阅读(126)  评论(0)    收藏  举报