基于callable多线程编程模拟龟兔赛跑过程

/**
 * 本程序实现龟兔赛跑模拟
 * 基于callable的多线程编程
 */
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
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 InterruptedException, ExecutionException {
        ExecutorService eService = Executors.newFixedThreadPool(2);//建立线程数目
        Race rabbit = new Race("小白兔", 100);  //创建实例
        Race tortoise = new Race("千年王八", 500);  //
        Future< Integer> num1 = eService.submit(rabbit);  //线程关联实例
        Future<Integer> num2 = eService.submit(tortoise);
        Thread.sleep(5000);
        rabbit.setFlag(false);
        tortoise.setFlag(false);
        System.out.println("小白兔跑了--->"+num1.get()+"步");
        System.out.println("千年王八跑了--->"+num2.get()+"步");

    }
}

class Race implements Callable<Integer>
{
        public Race(String name, long time) {
            this.time = time;
            this.name = name;
        }
        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        private String name;
        private long time;//延迟时间
        private boolean flag = true;
        private int num =0;


        @Override
        public Integer call() throws Exception {
            while(flag)
            {
                Thread.sleep(time);
                num++;
            }
            return num;
        }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值