Callable
* Callable<回传类型>
* 可以返回值
* 可以使用异常
0.class CDownloader implements Callable<Boolean>{}
1.创建目标对象:CDownloader cd=new CDownloader("图片地址","baidu.png");
2.创建执行服务:ExecutorService ser=Executors.newFixedThreadPool(1);
3.提交执行:Future<Boolean> result1=ser.submit(cd1);
4.获取结果:boolean r1=result1.get();
5.关闭服务:ser.shutdownNow();
package TCPUDPThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Executors;
/**
* 图片下载
* Callable<泛型>
* 可以返回值
* 可以使用异常
* @author pmc
*
*/
public class CDownloader implements Callable<Boolean>{
private static final String Excutors = null;
private String url;
private String name;
public CDownloader(String url,String name){
this.url=url;
this.name=name;
}
@Override
public Boolean call() throws Exception{
WebDownloader wd=new WebDownloader();
wd.download(url, name);
return true;
}
public static void main(String[] args) throws Exception {
CDownloader c1=new CDownloader("https://img.iplaysoft.com/wp-content/uploads/2019/overcooked/overcooked.jpg", "1.jpg");
CDownloader c2=new CDownloader("https://img.iplaysoft.com/wp-content/uploads/2019/overcooked/overcooked_screenshot1.jpg", "2.jpg");
CDownloader c3=new CDownloader("https://img.iplaysoft.com/wp-content/uploads/2019/overcooked/overcooked_screenshot2.jpg", "3.jpg");
//创建执行服务
ExecutorService ser=Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> res1=ser.submit(c1);
Future<Boolean> res2=ser.submit(c2);
Future<Boolean> res3=ser.submit(c3);
//获取结果
boolean r1=res1.get();
boolean r2=res2.get();
boolean r3=res3.get();
//关闭服务
ser.shutdown();
}
}
练习二
package TCPUDPThread;
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;
public class RacerTest implements Callable<Integer>{
private static String name;//胜利
// int temp=1;
public Integer call() throws Exception {
for(int temp=1;temp<=100;temp++){
//模拟休息
if(Thread.currentThread().getName().equals("pool-1-thread-1")&&temp%90==0){
Thread.sleep(2);
}
System.out.println(Thread.currentThread().getName()+"-->"+temp);
boolean flag=gameOver(temp);
if(flag){
return temp;
}
}
return null;
}
private boolean gameOver(int temp){
if(name!=null){
return true;
}else{
if(temp==100){
name=Thread.currentThread().getName();
System.out.println("name="+name);
return true;
}
}
return false;
}
public static void main(String[] args) throws Exception {
RacerTest a=new RacerTest();
// new Thread(a,"兔子").start();
// new Thread(a,"乌龟").start();
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(2);
// 提交执行
Future<Integer> res1 = ser.submit(a);
Future<Integer> res2 = ser.submit(a);
// 获取结果
Integer r1 = res1.get();
Integer r2 = res2.get();
System.out.println(r2);
// 关闭服务
ser.shutdown();
}
}