Lucky丶钉钉
2019-08-03 08:44
采纳率: 71.4%
浏览 997
已采纳

Java多线程模拟售票问题

package cn.zxyy.multiThread.saleTicket;

public class SaleTicketTest {
    public static void main(String[] args) {
        SaleTicket st = new SaleTicket();
        Thread t1 = new Thread(st,"A");
        Thread t2 = new Thread(st,"B");
        Thread t3 = new Thread(st,"C");
        Thread t4 = new Thread(st,"D");

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

package cn.zxyy.multiThread.saleTicket;

public class SaleTicket extends Thread {
    private static int ticket = 100;

    public SaleTicket(){

    }

    public SaleTicket(String name){
        super();
        this.setName(name);
    }

    @Override
    synchronized public void run() {
        super.run();

        while(true){
            if(ticket>0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("由"+Thread.currentThread().getName()+"号售票员卖第"+ticket+"张票");
                ticket--;
            }else {
                break;
            }
        }
    }
}

图片说明

问一问,为什么所有的票全部由线程A在售出,是程序有问题吗?

4条回答 默认 最新

相关推荐 更多相似问题