模拟抢票

一个对象,三个进程

package com.peanutist.day06;

public class TestThread03 implements Runnable{
   //有10张票
   public int nums = 10;
   //重写run方法
   public void run(){
       while (true) {
           if (nums <= 0) {
               System.out.println("没票了");
               break;
          }
           try {
               Thread.sleep(200);
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
           System.out.println(Thread.currentThread().getName() + "抢到了第" + nums-- + "票");
      }
  }

   public static void main(String[] args) {
       TestThread03 testThread03 = new TestThread03();
       Thread thread1 = new Thread(testThread03,"小明");
       Thread thread2 = new Thread(testThread03,"小花");
       Thread thread3 = new Thread(testThread03,"小杨");

       thread1.start();
       thread2.start();
       thread3.start();
  }
}

image-20210304225118582

为啥会出现这种情况呢?

posted on 2021-03-04 22:52  要给小八赚罐头钱  阅读(71)  评论(0)    收藏  举报