完整套路
java 通过实现Callable 接口来实现多线程相比较于继承Thread 接口和 实现Runnable 接口比较麻烦,但好处是可以有返回值。
基本套路:
1. 创建目标对象
2. 创建执行服务
3. 提交执行
4. 获取结果
5. 关闭服务
6.
继续方式一的下载图片,改写一下:
1 public class CDownload implements Callable<Boolean>{ 2 private String url; 3 private String name; 4 public CDownload(String url, String name) { 5 this.url = url; 6 this.name = name; 7 } 8 @Override 9 public Boolean call() throws Exception { 10 WebDownLoad wd = new WebDownLoad(); 11 wd.download(url, name); 12 System.out.println(name); 13 return true; 14 } 15 public static void main(String[] args) throws InterruptedException, ExecutionException { 16 CDownload td1 = new CDownload("http://img11.360buyimg.com/n1/s450x450_jfs/t1/95372/26/10103/109107/5e181892Eb698a3bc/2033bb2f00c38f93.jpg", "电脑.jpg"); 17 CDownload td2 = new CDownload("http://img14.360buyimg.com/n1/s450x450_jfs/t1/106229/22/9051/174570/5e0d4a59E099ec5cd/2501bf3e7f96c1fb.jpg", "键盘.jpg"); 18 CDownload td3 = new CDownload("http://img13.360buyimg.com/n1/s450x450_jfs/t1/5916/10/5128/160256/5b9f0e9bEbc9f4db4/14f062751af6ce26.jpg", "鼠标.jpg"); 19 // 创建执行服务 20 ExecutorService ser = Executors.newFixedThreadPool(3); 21 // 提交执行 22 Future<Boolean> r1 = ser.submit(td1); 23 Future<Boolean> r2 = ser.submit(td2); 24 Future<Boolean> r3 = ser.submit(td3); 25 // 获取结果 26 Boolean ret1 = r1.get(); 27 Boolean ret2 = r2.get(); 28 Boolean ret3 = r3.get(); 29 System.out.println(ret1 + "--" + ret2 + "--" + ret3); 30 // 关闭服务 31 ser.shutdownNow(); 32 } 33 34 }
简单写法:
1 package com.xzlf.testThread; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.FutureTask; 6 7 public class TestFutrueTask { 8 public static void main(String[] args) throws InterruptedException, ExecutionException { 9 // 创建任务 10 MyCall call = new MyCall(); 11 // 交给任务管理器 12 FutureTask<String> task = new FutureTask<String>(call); 13 // 创建代理类并启动线程 14 new Thread(task).start(); 15 System.out.println("获取结果-->" + task.get()); 16 System.out.println("任务是否执行完成-->" + task.isDone()); 17 } 18 } 19 20 21 class MyCall implements Callable<String>{ 22 @Override 23 public String call() throws Exception { 24 String[] strs = new String[]{"java", "pyhton", "html", "orcal", "tomcat"}; 25 String result = strs[(int) (Math.random()*5)]; 26 return result; 27 } 28 }