练习6

 

package zuoYe04;

public class BuyTicket implements Runnable {

    // 总票数
    private static int count = 10;

    // 抢票数
    private static int buy = 0;

//    static Object obj = new Object();
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {

            synchronized (this) {

                if (count > 0) {

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out
                            .println(Thread.currentThread().getName() + "抢到第" + (++buy) + "票,还剩余:" + (--count) + "张票");

                    if("黄牛党".equals(Thread.currentThread().getName())) {
                        
                        return;
                    }
                } else {

                    System.out.println("抢票结束!");
                    return;
                }

            }

        }
    }

}
package zuoYe04;

public class Test {

    public static void main(String[] args) {
        
        BuyTicket b = new BuyTicket();
        Thread t1 = new Thread(b,"桃跑跑");
        Thread t2 = new Thread(b,"张票票");
        Thread t3 = new Thread(b,"黄牛党");
        t1.start();
        t2.start();
        t3.start();
    }
}

 

 

posted @ 2019-08-07 10:47  AxeBurner  阅读(108)  评论(0编辑  收藏  举报