java_多线程Callable

实现Callable接口(了解即可)


1.实现Callable接口,需要返回值类型

2.重写call方法,需要抛出异常

3.创建目标对象

4.创建执行服务:ExecutorService =serExecutors.newFixedThreadPool(1);

5.提交执行 Future r1=ser.submit(t1);

6.获取结果:boolean rs1=r1.get();

7.关闭服务: ser.shutdown();

代码演示

package com.test1;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.io.FileUtils;

public class TestCallable implements Callable<Boolean>{

	private String url;// 图片地址
	private String name;// 图片名

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

	@Override
	public Boolean call() {
		WebDownloader web = new WebDownloader();
		web.dowmloader(url, name);
		System.out.println("下载了文件名为:" + name);
		return true;
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		TestCallable t1 = new TestCallable("https://img-home.csdnimg.cn/images/20210120054229.jpg", "1.jpg");
		TestCallable t2 = new TestCallable("https://img-home.csdnimg.cn/images/20210120054229.jpg", "2.jpg");
		TestCallable t3 = new TestCallable("https://img-home.csdnimg.cn/images/20210120054229.jpg", "3.jpg");
		//创建执行服务
		ExecutorService ser=Executors.newFixedThreadPool(3);
		//提交执行
		Future<Boolean> r1=ser.submit(t1);
		Future<Boolean> r2=ser.submit(t2);
		Future<Boolean> r3=ser.submit(t3);
		//获取结果
		boolean rs1=r1.get();
		boolean rs2=r2.get();
		boolean rs3=r3.get();
		//关闭服务
		ser.shutdown();

	}

}

class WebDownloader {
	public void dowmloader(String url, String name) {
		try {
			FileUtils.copyURLToFile(new URL(url), new File(name));
		} catch (IOException e) {

			e.printStackTrace();
			System.out.println("IO异常,dowmloader方法出现问题");
		}
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值