程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> java-程序糾錯,尋找原因,謝謝

java-程序糾錯,尋找原因,謝謝

編輯:編程綜合問答
程序糾錯,尋找原因,謝謝

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元”

最佳回答:


因為你這兩個線程沒有公用同一個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();
    }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved