模擬生產者與消費者實例
***********************核心方法類****************
package ;
class Queue
// key
{
int value;
boolean bFull = false;
public synchronized void put(int i) {
if (!bFull) {
value = i;
bFull = true;
notify();// 必須用在synchronized
}
try {
wait();// 必須捕獲異常
} catch (InterruptedException e) {
// TODO Auto
e
}
}
public synchronized int get() {
if (!bFull)
try {
wait();//進入
} catch (InterruptedException e) {
// TODO Auto
e
}
bFull = false;
notify();
return value;
}
}
*****************************************************************
************************生產者類********************************
package ;
class Producter extends Thread
{
Queue q;
Producter (Queue q)
{
this
}
public void run()
{
System
for(int i=
{
System
q
}
System
}
}
**********************************************************************
****************************消費者類*********************************
package ;
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this
}
public void run()
{
System
while(true)
{
System
System
}
}
}
************************************************************************
*******************************主函數調用類**********************************
package ;
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
Producter p=new Producter(q);
Consumer c=new Consumer(q);
p
c
}}
*****************************************************************
OK
wait方法——把線程放入wait set
notify方法——從wait set拿出線程
notifyAll方法——從wait set拿出所有線程
wait
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27459.html