##方法1 采用notify,wait
public class PublicBox {
private int apple = 0;
public synchronized void increace() {
while (apple ==5) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
apple++;
System. out .println("生成苹果成功!" );
notify();
}
public synchronized void decreace() {
while (apple ==0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
apple--;
System. out.println( "消费苹果成功!" );
notify();
}
public static void main(String []args) {
PublicBox box= new PublicBox();
Consumer con= new Consumer(box);
Producer pro= new Producer(box);
Thread t1= new Thread(con);
Thread t2= new Thread(pro);
t1.start();
t2.start();
}
}
//生产者代码(定义十次):
public class Producer implements Runnable {
private PublicBox box;
public Producer(PublicBox box) {
this .box = box;
}
@Override
public void run() {
for( int i=0;i<10;i++) {
Thread. sleep(30);
box.increace();
}
}
}
//消费者代码(同样十次):
public class Consumer implements Runnable {
private PublicBox box;
public Consumer(PublicBox box) {
this .box = box;
}
@Override
public void run() {
for( int i=0;i<10;i++)
{
System. out .println("Con: i " +i);
box.decreace();
}
}
}
##方法2 采用阻塞队列
public class PublicBoxQueue {
public static void main(String []args)
{
BlockingQueue publicBoxQueue= new LinkedBlockingQueue(5); //定义了一个大小为5的盒子
Thread pro= new Thread(new ProducerQueue(publicBoxQueue));
Thread con= new Thread(new ConsumerQueue(publicBoxQueue));
pro.start();
con.start();
}
}
//生产者:
package dsd;
import java.util.concurrent.BlockingQueue;
public class ProducerQueue implements Runnable {
private final BlockingQueue proQueue;
public ProducerQueue(BlockingQueue proQueue)
{
this .proQueue =proQueue;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i=0;i<10;i++)
{
try {
System. out .println("生产者生产的苹果编号为 : " +i); //放入十个苹果编号 为1到10
proQueue .put(i);
/*Thread.sleep(3000);*/
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
//消费者:
package dsd;
import java.util.concurrent.BlockingQueue;
public class ConsumerQueue implements Runnable {
private final BlockingQueue conQueue;
public ConsumerQueue(BlockingQueue conQueue)
{
this .conQueue =conQueue;
}
@Override
public void run() {
for (int i=0;i<10;i++)
{
try {
System. out .println("消费者消费的苹果编号为 :" +conQueue .take());
Thread. sleep(3000); //在这里sleep是为了看的更加清楚些
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
生产者与消费者问题
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...