|
1.定义一个实体类 实现callable接口
class Ract implements Callable<Integer>{
private String name;//姓名
private long time;//延时时间
private boolean flag = true; // 标记
private int step = 0 ;//步数
public Ract(String name, long time) {
super();
this.name = name;
this.time = time;
}
@Override
public Integer call() throws Exception {
while(flag){//当标记为true的时候,会一直走
Thread.sleep(time);//每隔多长时间走一步
step ++ ;
}
return step;
}
|
创建主线程public static void main(String args[]) throws InterruptedException, ExecutionException{
//创建一个定长的线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
Ract ract = new Ract("乌龟",1000);
Ract ract2 = new Ract("兔子",200);
Future<Integer> submit = pool.submit(ract);
Future<Integer> submit2 = pool.submit(ract2);
//设定时间为多长,时间到了,结束跑步
Thread.sleep(2000);
ract.setFlag(false);
ract2.setFlag(false);
Integer integer = submit.get();
Integer integer2 = submit2.get();
System.out.println("兔子走了:"+integer2+"步");
System.out.println("乌龟走了:"+integer+"步");
pool.shutdownNow();
} |
结果
![点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小](png/6440962-446753b2f90602aa.png)
----------------------------
原文链接:https://www.jianshu.com/p/696895a4680b
程序猿的技术大观园:www.javathinker.net
|
|