java的多线程买票问题,结果出现负数情况
如果线程为前面两个会出现票号为“0”的情况,如果线程大于2个的话,就会出现负数,请教该如果解决问题呢?
[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();//取双号票
new Thread(new SaleS(q)).start();//取单号票
}
}
class Q
{
private int tickets = 10;
public synchronized int get()
{
return tickets;
}
public synchronized void sale()
{
if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+
" is salling ticket "+ tickets--);
try
{
Thread.sleep(100);
}
catch(InterruptedException e){}
}
}
public synchronized void sale(boolean b)
{
if(tickets>0)
{
if((b && tickets % 2 ==1) || (!b && 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 saleSingle()
{
if(tickets>0)
{
if(tickets % 2 ==0)
{
System.out.println(Thread.currentThread().getName()+
" is waitting ");
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+
" is salling ticket "+ tickets--);
notify();
}
}
public synchronized void saleDouble()
{
if(tickets>0)
{
if(tickets % 2 ==1)
{
System.out.println(Thread.currentThread().getName()+
" is waitting ");
try {
wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
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()>0)
{
q.saleSingle();
}
}
}
class SaleD implements Runnable
{
Q q = null;
public SaleD(Q q)
{this.q = q;}
public void run()
{
while(q.get()>0)
{
q.saleDouble();
}
}
}
[/code]