1.定義一個(gè)實(shí)體類
實(shí)現(xiàn)callable接口
class?Ract?implements?Callable{
private?String name;//姓名
private?long?time;//延時(shí)時(shí)間
private?boolean?flag =?true;?// 標(biāo)記
private?int?step = 0 ;//步數(shù)
public?Ract(String name,?long?time) {
super();
this.name = name;
this.time = time;
}
@Override
public?Integer call()?throws?Exception {
while(flag){//當(dāng)標(biāo)記為true的時(shí)候,會(huì)一直走
Thread.sleep(time);//每隔多長(zhǎng)時(shí)間走一步
step ++ ;
}
return?step;
}
創(chuàng)建主線程
public?static?void?main(String args[])?throws?InterruptedException, ExecutionException{
//創(chuàng)建一個(gè)定長(zhǎng)的線程池
ExecutorService pool = Executors.newFixedThreadPool(2);
Ract ract =?new?Ract("烏龜",1000);
Ract ract2 =?new?Ract("兔子",200);
Future submit = pool.submit(ract);
Future submit2 = pool.submit(ract2);
//設(shè)定時(shí)間為多長(zhǎng)蝶溶,時(shí)間到了,結(jié)束跑步
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();
}
??結(jié)果
----------------------------
原文鏈接:www.javathinker.net