Created
September 27, 2018 08:35
-
-
Save zhanggang807/358d270967c8f297dba3329edcd6ade7 to your computer and use it in GitHub Desktop.
测试使用Callable,包含异常
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
//通过Callable接口模拟一个龟兔赛跑的例子 | |
public class CallableTest { | |
public static void main(String[] args) { | |
ExecutorService es = Executors.newFixedThreadPool(2); //开启两个线程 | |
Race tortoise = new Race("tortoise",1000); //每走一步需要1000毫秒 | |
Race rabbit = new Race("rabbit",500); //每走一步需要500毫秒 | |
Future<Integer> f1 = es.submit(tortoise); //自动在一个线程上执行 | |
Future<Integer> f2 = es.submit(rabbit); //自动在一个线程上执行 | |
try { | |
Thread.sleep(1000 * 3);//3秒之后 | |
tortoise.setFlag(false); | |
rabbit.setFlag(false); | |
System.out.println("tortoise move all step : " + f1.get()); | |
System.out.println("rabbit move all step : " + f2.get()); | |
es.shutdown(); //关闭调度器,这一步尤为重要,不关会一直耗损内存 | |
} | |
catch (InterruptedException e) { | |
System.out.println("外面接收异常 InterruptedException=" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
catch (ExecutionException e) {//其实会抛出执行异常 | |
System.out.println("外面接收异常 ExecutionException=" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
catch (Throwable t){ | |
System.out.println("外面接收异常 Throwable=" + t.getMessage()); | |
t.printStackTrace(); | |
} | |
} | |
} | |
class Race implements Callable<Integer>{ | |
private String name; //参赛者名称 | |
private long time; //参赛者每走一步需要花的时间 | |
private int step; //参赛者总共走了多少步 | |
private boolean flag = true; //比较时间是否结束 默认为未结束 | |
public Race(){} | |
public Race(String name, long time){ | |
this.name = name; | |
this.time = time; | |
} | |
@Override | |
public Integer call() throws Exception { | |
while(flag){ | |
Thread.sleep(time); //模拟参赛者走一步需要花的时长 | |
step++; //比赛时间尚未结束,步数加1 | |
System.out.println("里面call方法抛出异常"); | |
throw new Exception("测试call方法中抛异常"); | |
} | |
return step; //一共走了多少步 | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public long getTime() { | |
return time; | |
} | |
public void setTime(long time) { | |
this.time = time; | |
} | |
public int getStep() { | |
return step; | |
} | |
public void setStep(int step) { | |
this.step = step; | |
} | |
public boolean isFlag() { | |
return flag; | |
} | |
public void setFlag(boolean flag) { | |
this.flag = flag; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment