卖票

package ThreadTest;

/*
 * 卖票系统:
 *     票数固定,实现Runnable接口,票数共享
 *  有四个窗口卖票:有四个进程在同时卖
 *  
 */
class MP implements Runnable {
    // 为了让多个线程对象共享这100张票,我们其实应该用静态修饰
    private static int i = 20;
    //定义锁,锁要在run()方法外面定义,用private修饰
    private Object obj = new Object();
    //锁不能为空
    //private Object obj = null;

    public void run() {
        ;
        // for( ;i >0; i--){
        // System.out.println(Thread.currentThread().getName() + "  " + i);
        // }
        //
//        while (true) {
//            if (i > 0) {
//                
//                try {
//                    
//                    Thread.sleep(100);
//                    System.out.println("睡了1秒");
//                } catch (InterruptedException e) {
//                    // TODO 自动生成的 catch 块
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName() + "正在出售第"
//                        + (i--) + "张票");
//            }
//        }
        while (true){
            //锁只需要放在需要锁住的代码块,锁内的代码每次只能进一个人,进去一个,其他就休眠。
            synchronized (obj) {
                if (i > 0) {
                    try {
                        Thread.sleep(100);
                        System.out.println("睡了1秒");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第"
                            + (i--) + "张票");
                }
            }
            
        }

    }
}

public class cinemaDemo {
    public static void main(String[] args) {
        MP m = new MP();
        Thread t1 = new Thread(m, "窗口1");
        Thread t2 = new Thread(m, "窗口2");
        Thread t3 = new Thread(m, "窗口3");
        Thread t4 = new Thread(m, "窗口4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
原文地址:https://www.cnblogs.com/changzuidaerguai/p/6523085.html