萨达所大所多

 

 

package com.ljy.test;
//模拟龟兔赛跑
public class Race implements Runnable{
    //胜利者
    private static String winner;

    @Override
    public  void run() {
//
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        int num=0;
        for (int i = 0; i <= 1000; i++) {
            //判断比赛是否结束
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            if (Thread.currentThread().getName()=="兔子"){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag=gameOver(i);

            if (flag){
                break;
            }
//                num++;
            System.out.println(Thread.currentThread().getName()+"----->跑了"+i+"步");
        }
//        try {
//            Thread.sleep(3100);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }
    //判断是否完成了比赛
    private boolean gameOver(int steps){
        //判断是否有胜利者
        if (winner!=null){
            return true;
        }
        if (steps==1000){
            winner=Thread.currentThread().getName();
            System.out.println("Winner为:"+winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

你可能感兴趣的:(java,开发语言)