public class ThreadDemo {
  public static void main(String[] args) {
  /*
  需求:
  某电影院目前正在上映国产大片,共有100张票,而它有3个窗口卖票,请设计一个程序模拟该电影院卖票
  */

  //创建线程对象
  MyThread t1 = new MyThread();
  MyThread t2 = new MyThread();
  MyThread t3 = new MyThread();

  //起名字
  t1.setName("窗口1");
  t2.setName("窗口2");
  t3.setName("窗口3");

  //开启线程
  t1.start();
  t2.start();
  t3.start();

  }

}

public class MyThread extends Thread {

  //表示这个类所有的对象,都共享ticket数据
  static int ticket = 0;//0 ~ 99

  @Override
  public void run() {
  while (true) {
  synchronized (MyThread.class) { //锁对象一定是惟一的
  //同步代码块 
  if (ticket < 100) {
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    ticket++;
    System.out.println(getName() + "正在卖第" + ticket + "张票!!!");
    } else {
    break;
    }
}
}
}

 

}

posted on 2023-12-14 23:04  防守三巨臀  阅读(3)  评论(0编辑  收藏  举报