筆記20200513:多線程【案例:龜兔賽跑】

案例:龜兔賽跑
package com.chengguo.線程;

/**
 * 模擬:龜兔賽跑
 */
public class Demo_20200509003_ThreadRace implements Runnable {
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {

            //模擬兔子休息
            if (Thread.currentThread().getName().equals("兔子")&&(i+1)%10==0){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //判斷比賽是否結束
            boolean flag = gameOVer(i);
            //若是比賽結束,程序中止
            if (flag) {
                break;
            }

            System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
        }
    }

    //判斷是否完成比賽
    private boolean gameOVer(int step) {
        //已經存在勝利者
        if (winner != null) {
            return true;
        } else {
            if (step >= 100) {
                //獲取勝利者名字(線程名字)
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        //建立runnable接口的實現類對象
        Demo_20200509003_ThreadRace dt = new Demo_20200509003_ThreadRace();
        //建立一個線程對象,經過線程對象來開啓線程
        new Thread(dt, "兔子").start();
        new Thread(dt, "烏龜").start();
    }
}
相關文章
相關標籤/搜索