预想实现轮番取[color=red]单数[/color]票和[color=red]双号[/color]票的多线程出票过程
执行结果发现:
如果只执行两个进程,程序会卖出票号为“0”的票,如果再增加出票的线程就出现线程为[color=red]负[/color]数的情况了
[code="java"]
public class myFirst
{
public static void main(String[] args)
{
Q q = new Q();
new Thread(new SaleS(q)).start();
new Thread(new SaleD(q)).start();
new Thread(new SaleS(q)).start();
new Thread(new SaleD(q)).start();
}
}
class Q
{
private int tickets = 10;
public synchronized int get()
{
return tickets;
}
public synchronized void saleSingle()
{
if(tickets>0)
{
if(tickets % 2 ==0)
{
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+
" is salling ticket "+ tickets--);
notify();
}
}
public synchronized void saleDouble()
{
if(tickets>0)
{
if(tickets % 2 ==1)
{
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+
" is salling ticket "+ tickets--);
notify();
}
}
}
class SaleS implements Runnable
{
Q q = null;
public SaleS(Q q)
{this.q = q;}
public void run()
{
while(q.get()>=1)
{
q.saleSingle();
}
}
}
class SaleD implements Runnable
{
Q q = null;
public SaleD(Q q)
{this.q = q;}
public void run()
{
while(q.get()>=2)
{
q.saleDouble();
}
}
}
[/code]