public class SaleTicketThread{
    public static void main(String[] args) {

        //创建共享资源对象
        TicketThread tt = new TicketThread();

        //创建线程

        Thread t1 = new Thread(tt,"窗口一");
        Thread t2 = new Thread(tt,"窗口二");
        Thread t3 = new Thread(tt,"窗口三");
        Thread t4 = new Thread(tt,"窗口四");

        //线程准备就绪

        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }
}

class TicketThread implements Runnable{

    //票数
    private int tickets = 50;
    //锁对象
    Object obj = new Object();

    @Override
    public void run() {


           while (true){


                   //同步
                   synchronized (obj) {

                       if (tickets > 0) {

                           System.out.println(Thread.currentThread().getName() + "卖出第:" + tickets-- + " 张票");
                       }else{
                           break;
                       }
                   }

               try {
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }


            System.out.println(Thread.currentThread().getName()+"卖完了");

    }
}
Last modification:May 5th, 2020 at 10:44 pm
如果觉得我的文章对你有用,请随意赞赏