Java并发编程:CallableFuture和FutureTask 实现龟兔赛跑

Posted luzhouxiaoshuai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java并发编程:CallableFuture和FutureTask 实现龟兔赛跑相关的知识,希望对你有一定的参考价值。

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并发编程:CallableFuture和FutureTask 实现龟兔赛跑的主要内容,如果未能解决你的问题,请参考以下文章

Java并发编程(十四):CallableFuture和FutureTask(转载)

Java并发编程:CallableFuture和FutureTask

Java并发编程- CallableFuture和FutureTask

java并发编程:CallableFuture和FutureTask

Java并发编程:CallableFuture和FutureTask

Java并发编程:CallableFuture和FutureTask