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();
}
结果
QQ图片20180523114955.png
更多交流 qq群:552113611
码云源码:https://gitee.com/zhangqiye/Thread
网友评论