標籤:future package als cut 關閉 throws new set 線程池
1、不清楚的看部落格http://www.cnblogs.com/dolphin0520/p/3949310.html
我們使用上面的代碼來實現一個龜兔賽跑
package com.weiyuan.test;import java.util.concurrent.Callable;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Main { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int countTime = 4000;//跑步的總時間 ExecutorService service = Executors.newFixedThreadPool(2); Task tuzi = new Task("兔子", 500); Task wugui = new Task("烏龜", 1000); Future<Integer> rst1 = service.submit(tuzi); Future<Integer> rst2 = service.submit(wugui); /** * 跑步總的時間長度是4秒 * */ Thread.sleep(countTime); /* * 跑步時間到了,記得退出線程 * */ tuzi.setFlag(false); wugui.setFlag(false); Integer num1 = rst1.get(); Integer num2 = rst2.get(); System.out.println("兔子"+"跑了"+num1+"步"); System.out.println("烏龜"+"跑了"+num2+"步"); /** * 關閉線程池 * */ service.shutdown(); } public static class Task implements Callable<Integer>{ /** * 兔子還是烏龜 * time 兔子和烏龜跑步的時間 * 跑步時間大了停止線程的退出 * 跑步的步數 * */ private String name; private long time; private boolean flag = true; private int step = 0; public Task(String name, long time) { this.name = name; this.time = time; } @Override public Integer call() throws Exception { // TODO Auto-generated method stub while(flag){ Thread.sleep(time); step ++ ; } 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 boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } }}
程式的運行結果是:
兔子跑了9步
烏龜跑了5步
Java並發編程:Callable、Future和FutureTask 實現龜兔賽跑