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();
}
}