Java Web知识Java学习笔记Java 杂谈

多线程的例子——模拟购票功能

2016-11-13  本文已影响773人  GuaKin_Huang


Ticket

public class Ticket {
    public Ticket(int number) {
        this.number = number;
    }
     int number;
}

TicketThread

public class TicketThread extends Thread {
    private String name;
    private Ticket ticket;
    private int count;

    public TicketThread(String name, Ticket ticket) {
        this.name = name;
        this.ticket = ticket;
        count = ticket.number;
    }

    @Override
    public void run() {
        for (int i = 1; i <= count; i++) {
            try {
                synchronized (ticket) {
                    if (ticket.number > 0) {
                        ticket.number--;
                        Thread.sleep(100);
                        System.out.println(name + " 卖了 " + i + " 张票"
                                + ", 余票:" + ticket.number);
                    } else {
                        System.out.println(name + " 没有票了");
                        break;
                    }

                }
            Thread.sleep(500);//增加卖票输出到下一次卖票过程的间隔时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

测试类

public class TicketTest {
    public static void main(String[] args){
        Ticket ticket = new Ticket(30);

        TicketThread t1 = new TicketThread("T1", ticket);
        TicketThread t2 = new TicketThread("T2", ticket);
        TicketThread t3 = new TicketThread("T3", ticket);

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

结果

result.gif
上一篇下一篇

猜你喜欢

热点阅读