目前有三个窗口同时出售20张票,那么用java怎么实现呢?

1.通过继承Thread类

public class Ticket extends Thread{  //继承Thread类
     private static int tickets=20;

      @Override
 public void run() {

     while(true){

    synchronized (Ticket.class) {  //这一句话是核心,synchronized锁定的是对象的类

       if (tickets <1) {
            System.out.println("票卖完了");
            System.exit(0);    //正常退出,如果用break的话,
             }

              System.out.println("卖出了第" + tickets + "张票");
                tickets--;

             }

         }    
      }
}

写控制台

public class Demo01 {
    public static void main(String[] args) {
        Ticket st01 = new Ticket();
        Ticket st02 = new Ticket();
        Ticket st03 = new Ticket();


        st01.start();
        st02.start();
        st03.start();

    }
}

2.通过实现runnable接口

public class Station01 implements Runnable{

    private int total = 100;
    //private int no = total+1;
    private Object obj = new Object();
    @Override
    public void run() {   //执行线程

        while(true) {    //不断的循环,配合下面的if语句使用

            synchronized (this.obj) {  //锁

                if (this.total>0) {  //这里用if完成了一次循环,自己都吓了一跳,不过确实是可以的


                    String msg =Thread.currentThread().getName()+" 售出第   "+(this.total) +"  张票";
                    System.out.println(msg);

                    this.total--;
                }else {
                    System.out.println("票已经卖完了");
                    System.exit(0);    //正常的退出程序
                }
            }
        }    
    }    
}

控制台

public class Demo02 {
public static void main(String[] args) {

    Station01 demo01 = new Station01();

    Thread station1 = new Thread(demo01,"1号窗口");
    Thread station2 = new Thread(demo01,"2号窗口");
    Thread station3 = new Thread(demo01,"3号窗口");
    Thread station4 = new Thread(demo01,"4号窗口");


    station1.start();
    station2.start();
    station3.start();
    station4.start();
}
}


一个好奇的人