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

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(); } }

    推荐阅读