初识并发问题_龟兔赛跑

初始并发问题

public class TestThread implements Runnable{
    //多个线程同时操作同一个对象

    //总数
    private int ticketNums = 10;
    @Override
    public void run() {
        while (true){
            if (ticketNums<= 0){break;}
            try {
                //模拟延时
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ ticketNums-- +"票");
        }
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();

        new Thread(testThread,"A").start();
        new Thread(testThread,"B").start();
        new Thread(testThread,"C").start();
    }


}

image-20210206223831171

发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱

龟兔赛跑

//模拟龟兔赛跑
public class Race implements Runnable{

    //胜利者
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //模拟兔子睡觉
            if (Thread.currentThread().getName().equals("兔子")&&i%10 ==0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean flag = gameOver(i);
            if (flag){
                break;
                //如果比赛结束了就停止程序
            }
            System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
        }
    }
    //判断是否完成比赛
    private boolean gameOver(int steps){
        if (winner!=null){//已经存在胜利者了
            return true;
        }{
            if (steps >=100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is"+winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();

        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }


}

  1. 赛道距离100,要离终点越来越近
  2. 判断比赛是否结束
  3. 打印出胜利者
  4. 龟兔赛跑开始
  5. 故事中兔子需要睡觉,所以模拟兔子睡觉
  6. 最终,乌龟赢得比赛
posted @ 2021-03-03 08:31  PitayaWalk  阅读(15)  评论(0)    收藏  举报