基于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 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
{
        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;
        }
}

你可能感兴趣的:(java程序)