?? java生產者-消費者.txt
字號:
class Producter extends Thread
{
Queue q;
Producter (Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<10;i++)
{
q.put(i);
System.out.println("producter :"+i);
}
}
}
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println("Consumer:"+q.get());
}
}
}
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-generated catch block
e.printStackTrace();
}
}
public synchronized int get()
{
if(!bFull)
try
{
wait(); // 等待生產者寫入數據
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bFull=false; // 通知生產者數據已經被取走,可以再次寫入數據
notify();
return value;
}
}
public class test //測試類
{
public static void main(String[] args)
{
Queue q=new Queue();
Producter p=new Producter(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}
}
問題補充:System.out.println("Consumer:"+q.get());
}
}
}
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-generated catch block
e.printStackTrace();
}
}
public synchronized int get()
{
if(!bFull)
try
{
wait(); // 等待生產者寫入數據
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bFull=false; // 通知生產者數據已經被取走,可以再次寫入數據
notify();
return value;
}
}
public class test //測試類
{
public static void main(String[] args)
{
Queue q=new Queue();
Producter p=new Producter(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -