プロデューサーとコンシューマーのアプリケーション シナリオの例
例えば、ユーザー登録の際に携帯電話番号認証が必要になる場合がありますが、携帯電話番号認証には時間がかかり、上限もあり、同時に多数のユーザーが携帯電話番号認証を利用すると、携帯電話番号認証を利用する際に待ち時間が発生します。ライン。
コード例
生産者スレッドは饅頭をかごに入れ、消費者スレッドは饅頭を取り出します。バスケットが最大 6 個の饅頭を保持できると仮定すると、バスケットがいっぱいになると、プロデューサー スレッドは待機する必要があります。コンシューマーが饅頭を取り出すと、プロデューサー スレッドがアクティブになり、バスケット内の饅頭が取り出されると、コンシューマー スレッドは待機する必要があります。
package com.test.producerConsumer;
public class Basket {
int index=0;
ManTou[] manTous=new ManTou[6];
//往篮子中放馒头
public synchronized void push(ManTou manTou)
{
//篮子满了 需要等待
if(index==6)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify(); //唤醒的是pop中的wait方法 一旦放馒头了 则说明篮子中有馒头了 取馒头的方法不用等了
this.manTous[index]=manTou;
index++;
}
//从篮子中取馒头
public synchronized ManTou pop()
{
if(index==0)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.notify(); //唤醒的是push中的wait方法 一旦取馒头了 则说明篮子有空位了 放馒头的行为就不用等了
index--;
return this.manTous[index];
}
}
package com.test.producerConsumer;
public class ManTou {
int id;
public ManTou(int id)
{
this.id=id;
}
public String toString()
{
return "ManTou[id="+this.id+"]";
}
}
package com.test.producerConsumer;
public class Consumer extends Thread{
Basket basket=null;
public Consumer(Basket basket)
{
this.basket=basket;
}
//执行任务
public void run()
{
for(int i=1;i<=20;i++)
{
ManTou manTou= this.basket.pop();
System.out.println("消费了"+manTou);
try {
this.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.test.producerConsumer;
public class Producer extends Thread{
Basket basket=null;
public Producer(Basket basket)
{
this.basket=basket;
}
//执行任务
public void run()
{
for(int i=1;i<=20;i++)
{
ManTou manTou=new ManTou(i);
basket.push(manTou);
System.out.println("生产了"+manTou);
try {
this.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.test.producerConsumer;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Basket basket=new Basket();
Producer producer=new Producer(basket);
Consumer consumer=new Consumer(basket);
producer.start();
consumer.start();
}
}