线程的创建之实现Callable接口

1. 过程

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

2. 使用

public class Demo6 implements Callable<Boolean> {

    private String url;
    private String name;

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

    @Override
    public Boolean call() {
        new WebDownloader1().downloader(url, name);
        System.out.println("下载的文件名为" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Demo6 t1 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "1.png");
        Demo6 t2 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "2.png");
        Demo6 t3 = new Demo6("https://cdn.jsdelivr.net/gh/rootwhois/oss@main/uPic/image-20210820235038265.png", "3.png");

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Future<Boolean> submit = executorService.submit(t1);
        Future<Boolean> submit1 = executorService.submit(t2);
        Future<Boolean> submit2 = executorService.submit(t3);

        Boolean rs1 = submit.get();
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:52

results matching ""

    No results matching ""