//控制售票過程,每張票被生產並被賣出後纔可以生產下一張票
public class commuicationThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ticket1 t=new ticket1(20);
new productor1(t).start();
new seller1(t).start();
}
}
class ticket1
{
int size;
int number=0;
boolean available=false;
public ticket1(int size)
{this.size=size;}
public synchronized void put()
{if(available)
try {
wait();
} catch (InterruptedException e) {}
System.out.println("Producer puts ticket"+(++number));
available=true;
notify();
}
public synchronized void sell()
{ if(!available)
try {
wait();
} catch (InterruptedException e) {}
System.out.println("Consummer buys ticker"+(number));
available=false;
notify();
if(number==size)
number=size+1;
}
}
class productor1 extends Thread
{
ticket1 t=null;
public productor1(ticket1 t)
{this.t=t;}
public void run()
{while(t.number<t.size)
t.put();
}
}
class seller1 extends Thread
{
ticket1 t=null;
public seller1(ticket1 t)
{this.t=t;}
public void run()
{
while(t.number<=t.size)
{t.sell();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
}
}
/*
1.根據售票的兩個情況爲基礎設計,當有票買時暫停生產,沒票賣時暫停銷售
2.Thread類
wait() 暫停線程在對象x上的執行並將線程放入wait池,並釋放對象x 的鎖旗標,等待其它進程在x對象上調用notify()或notifyAll()方法,才能獲得鎖旗標並繼續往後執行
notify() 喚醒正在等待該對象鎖旗標的第一個線程*/