import java.util.Random;
public class Seller
{
public static void main(String[] args)
{
SellerTicket st = new SellerTicket();
st.zhang.start();
st.li.start();
st.chen.start();
}
}
class SellerTicket implements Runnable
{
public int[] moneyArray =
{
5, 10, 20
};
public Random random = new Random();
public Thread zhang;
public Thread li;
public Thread chen;
public int fiveMoney = 1;
public int tenMoney;
public int twentyMoney;
public SellerTicket()
{
zhang = new Thread(this);
li = new Thread(this);
chen = new Thread(this);
}
public void run()
{
while (true)
{
if(Thread.currentThread() == zhang)
{
seller(this.moneyArray[random.nextInt(3)]);
}
else if(Thread.currentThread() == li)
{
seller(this.moneyArray[random.nextInt(3)]);
}
else if(Thread.currentThread() == chen)
{
seller(this.moneyArray[random.nextInt(3)]);
}
}
}
public synchronized void seller(int receiveMoney)
{
if(receiveMoney == 5)
{
this.fiveMoney++;
System.out.println("收您5块钱,这是您的票");
}
else if(receiveMoney == 10)
{
while (this.fiveMoney < 1)
{
System.out.println("对不起,10块钱太大了,请您等待...");
try
{
wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.tenMoney++;
this.fiveMoney--;
System.out.println("收您10块钱,找您5块钱,这是您的票");
}
else if(receiveMoney == 20)
{
while (this.fiveMoney < 1 || this.tenMoney < 1)
{
System.out.println("对不起,20块钱太大了,请您等待...");
try
{
wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.twentyMoney++;
this.fiveMoney--;
this.tenMoney--;
System.out.println("收您20块钱,找您15块钱,这是您的票");
}
notifyAll();
}
}
原文:https://www.cnblogs.com/alichengxuyuan/p/12578053.html