当前位置: 移动技术网 > IT编程>开发语言>Java > 三个窗口同时卖票 用 实现Runnable方式

三个窗口同时卖票 用 实现Runnable方式

2020年07月22日  | 移动技术网IT编程  | 我要评论
package com.hp.zuoye
public class chepaio implements Runnable {
      //总票数
    public static int count=100;
      //定义一个静态对象
    public static Object object=new Object();
    @Override
    public void run() {
       //死循环卖票
            try {
           //模拟 卖票耗时操作
                while (true){
                    Thread.sleep(2000);
         //synchronized 操作 ,使用位置. 哪个地方出问题 ,就放到对应位置
                synchronized (object){

                    if (count>0){
                        System.out.println("当前剩余:"+count+"张");
                        count--;//每卖出1张 ,要减去1张
                    }else{
                        System.out.println("当前车票已售完");
                        System.exit(0); //退出程序
                    }

                }
            }


        } catch (InterruptedException e) {
                e.printStackTrace();
            }

    }
    public static void main(String[] args) {
        chepaio cp1=new chepaio();
        chepaio cp2=new chepaio();
        chepaio cp3=new chepaio();
        //线程
        Thread thread1=new Thread(cp1);
        Thread thread2=new Thread(cp2);
        Thread thread3=new Thread(cp3);
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

本文地址:https://blog.csdn.net/ppdpn/article/details/107465589

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网