售票同步锁

来源:互联网 发布:golang sleep 在哪里 编辑:程序博客网 时间:2024/06/05 04:18

要求:

实现多窗口售票机制


public class Ticket {/** * 售票员卖票问题 */public static void main(String[] args) {//实例化该窗口类的对象TicketWindow tw = new TicketWindow();//将该对象放入三个线程Thread t1 = new Thread(tw);Thread t2 = new Thread(tw);Thread t3 = new Thread(tw);//启动三个线程t1.start();t2.start();t3.start();}}/** * 售票窗口 * */class TicketWindow implements Runnable{//总票数private   int num = 2000;public   void  run(){while(true){//同步锁,this代表该类的对象synchronized(this){if(num > 0){try {//休眠线程1秒,必须捕获异常Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"正在卖出第"+num+"张票");num--;}else {break;}}}}}


0 0
原创粉丝点击