【JUC编程】线程的创建(三)

创建步骤:

  • 实现Callable接口,需要返回值类型
  • 重写call方法,需要抛出异常
  • 创建目标对象
  • 执行创建任务:ExecutorService ser=Executor.newFixedThreadPool(1);
  • 提交执行:Future result=ser.submit(t1);
  • 获取结果:boolean r=result.get()
  • 关闭服务:ser.shutdownNow();

入门案例:

从网络下载图片:

package Callable;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author jitwxs
 * @date 2021年04月11日 19:36
 */
public class CallableTest implements Callable<Boolean> {
        @Override
        public Boolean call() throws Exception {
                WebDownloader webDownloader=new WebDownloader();
                webDownloader.downloader(url,name);
                System.out.println("下载的文件名为:"+name);
                return true;
        }
        private String url;//网络图片地址
        private String name;//保存的文件名

        public CallableTest(String url, String name) {
                this.url = url;
                this.name = name;
        }



        public static void main(String[] args) throws Exception{
                CallableTest d1=new CallableTest("https://profile.csdnimg.cn/8/4/3/1_m0_46495243","1.jpg");
                CallableTest d2=new CallableTest("https://imgcdn.toutiaoyule.com/20210407/20210407134042114529a_t.jpeg","2.jpeg");
                CallableTest d3=new CallableTest("https://lupic.cdn.bcebos.com/20191206/2001330442%2318.jpg","3.jpg");
                ExecutorService ser= Executors.newFixedThreadPool(3);
                Future<Boolean> result1=ser.submit(d1);
                Future<Boolean> result2=ser.submit(d2);
                Future<Boolean> result3=ser.submit(d3);
                boolean r1=result1.get();
                boolean r2=result2.get();
                boolean r3=result3.get();
                ser.shutdownNow();


        }
}
//下载器
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,Download方法");
                }
        }
}

  • 结果
    【JUC编程】线程的创建(三)

【JUC编程】线程的创建(三)

上一篇:厚积薄发打卡Day50:JUC并发编程(从Synchronized 到 AQS)


下一篇:JUC安全类型的集合