欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-28 18:23:12
package com.hp.zuoyepublic class chepaio implements Runnable { public static int count=100; public static Object object=new Object(); @Override public void run() { try { while (true){ Thread....
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

相关标签: 线程 多线程