java多线程经典问题--购票问题

版权声明:欢迎转载,注明出处 https://blog.csdn.net/jklcl/article/details/81209560

java多线程经典问题–购票问题

要求:

  • 1、三个窗口同时售票,一共20张票
  • 2、售票期间互不干扰

想法:

  • 1、多线程
  • 2、死锁
  • 3、静态变量的票数
class threadDemo extends Thread{
    public String Tname;//定义窗口名字
    public Thread thread;//线程
    static Object ob = "ob";//加一把锁,随便赋值
    static int num = 20;//票数

    public threadDemo(String name) {
        Tname = name;
    }

    public void run() {
        while(num > 0)
        {
            //上锁,在一个用户执行完一个操作之前,其他用户不能操作
            synchronized (ob) {
                if(num > 0) {
                    System.out.println(Tname+"第"+num+"张票已售出");
                    num--;
                }
                else {
                    System.out.println("张票已售完");
                }
            }
            try {
                //添加一段时间
                this.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public void start() {
        if(thread == null) {
            thread = new Thread(this, Tname);
            thread.start();
        }
    }

}

public class station {

    public static void main(String[] args) {
        //定义三个进程窗口
        threadDemo sta1 = new threadDemo("窗口一");
        threadDemo sta2 = new threadDemo("窗口二");
        threadDemo sta3 = new threadDemo("窗口三");

        sta1.start();
        sta2.start();
        sta3.start();

    }
}

猜你喜欢

转载自blog.csdn.net/jklcl/article/details/81209560