package jd1908_corejava.ch15.work; //线程经典问题--龟兔赛跑问题 public class Race { public static void main(String[] args) { RabbitAndTurtle rabbit = new RabbitAndTurtle(); rabbit.setName("兔子"); RabbitAndTurtle turtle = new RabbitAndTurtle(); turtle.setName("乌龟"); rabbit.start(); turtle.start(); } } class RabbitAndTurtle extends Thread { private int num; // boolean类型默认初始值为false private static boolean flag; //run执行完毕后线程就会死亡,关闭 //yield(),释放资源,回到run的顶部 @Override public void run() { while (num < 100) { if (flag) { // 线程终止 break; } if (Math.random() < 0.3 && Thread.currentThread().getName().equals("兔子")) { num += 2; System.out.println("兔子跑了" + num); if (num == 100) { System.out.println("兔子赢了"); break; } Thread.yield(); } if (Math.random() > 0.3 && Thread.currentThread().getName().equals("乌龟")) { num += 1; System.out.println("乌龟跑了" + num); if (num == 100) { System.out.println("乌龟赢了"); break; } Thread.yield(); } } if (num == 100) { flag = true; } } }
注意:两个线程是相互独立的,但是flag是共享的
同种类型不用的实例化对象静态资源是共享!
来源:https://www.cnblogs.com/fyscn/p/11358448.html