【多線程】線程創建方式三:實現callable接口
線程創建方式三:實現callable接口
代碼示例:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/**
* @Description 線程創建方式三:實現callable接口
* @Author hzx
* @Date 2022-03-26
*/
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 webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下載了文件:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222236055-1081286442.png","1.jpg");
TestCallable t2 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222535845-769752621.png","2.jpg");
TestCallable t3 = new TestCallable(
"https://img2022.cnblogs.com/blog/1617979/202203/1617979-20220315222316724-2013137843.png","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();
//打印返回結果
System.out.println("rs1返回值:"+rs1);
System.out.println("rs2返回值:"+rs2);
System.out.println("rs3返回值:"+rs3);
//關閉服務
ser.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異常,下載方法出現問題");
}
}
}
輸出結果:
下載了文件:1.jpg
下載了文件:3.jpg
下載了文件:2.jpg
rs1返回值:true
rs2返回值:true
rs3返回值:true
callable的好處:
- 1.可以定義返回值;
- 2.可以拋出異常。

浙公網安備 33010602011771號