2 jkuco jkuco 于 2013.06.18 11:05 提问

程序纠错,寻找原因,谢谢

public class maipiao implements Runnable{

    Thread wang,li;


    maipiao()
    {
        wang = new Thread(this);
        li = new Thread(this);
    }

    @Override
    public void run() {
        if(Thread.currentThread()== wang)
        {
            new saleTicket().rule(5);
        }
        else if(Thread.currentThread() == li)
        {
            new saleTicket().rule(20);
        }

    }
  public static void main(String[] args) {
    maipiao a = new maipiao();
    a.wang.start();
    a.li.start();
}
}

public class saleTicket {
    int ticket5 = 2,ticket10 = 0 ,ticket20=0;
    public synchronized  void rule(int money)
    {
        if(money == 5)
        {
            ticket5 = ticket5+1;
            System.out.println("给你票,你的钱正好");
        }
        else if(money == 20)
        { 
            while(ticket5<3){
            try {
            wait();
            } catch (InterruptedException e) {}
            }
            ticket20 = ticket20+1;
            ticket5 = ticket5 - 3;
            System.out.println("给你票,你给我20,找你15元");
        }
        notifyAll();
    }
}

为什么运行后不出现“给你票,你给我20,找你15元”

1个回答

u011121287
u011121287   2013.06.18 23:14
已采纳

因为你这两个线程没有公用同一个saleTicket对象对你程序修改如下:

public class maipiao implements Runnable {

    Thread wang, li;

    saleTicket saleTicket=new saleTicket();

    maipiao() {
        wang = new Thread(this);
        li = new Thread(this);
    }

    @Override
    public void run() {
        if (Thread.currentThread() == wang) {
            saleTicket.rule(5);
        } else if (Thread.currentThread() == li) {
            saleTicket.rule(20);
        }

    }

    public static void main(String[] args) {
        maipiao a = new maipiao();
        a.wang.start();
        a.li.start();
    }
}

class saleTicket {
    int ticket5 = 2, ticket10 = 0, ticket20 = 0;

    public synchronized void rule(int money) {

        System.out.println("money:"+money+"|"+ticket5);
        if (money == 5) {
            ticket5 = ticket5 + 1;
            System.out.println("给你票,你的钱正好");
        } else if (money == 20) {
            while (ticket5 < 3) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            ticket20 = ticket20 + 1;
            ticket5 = ticket5 - 3;
            System.out.println("给你票,你给我20,找你15元");
        }
        notifyAll();
    }
}
jkuco
jkuco 谢谢,问题已经解决了。
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!