如何将经典Java多线程案例——生产者消费者问题,改写成长尾词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计706个文字,预计阅读时间需要3分钟。
通过Java实现,5个盘子,生产者不断的产生热狗,最多5个。盘子上放有热狗,消费者不断的吃热狗,直到吃完。
javapublic class ProducerAndConsumer { // 盘子数量 private static final int DISHES=5; // 热狗数组,充当盘子 private static final int[] hotDogs=new int[DISHES]; // 盘子当前状态 private static int count=0;
public static void main(String[] args) { // 创建生产者和消费者线程 Thread producer=new Thread(new Producer()); Thread consumer=new Thread(new Consumer()); // 启动线程 producer.start(); consumer.start(); }
// 生产者线程 static class Producer implements Runnable { @Override public void run() { while (true) { synchronized (hotDogs) { if (count >=DISHES) { try { hotDogs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } hotDogs[count]=1; // 生产热狗 count++; System.out.println(生产者生产热狗,盘子: + count); hotDogs.notifyAll(); } } } }
// 消费者线程 static class Consumer implements Runnable { @Override public void run() { while (true) { synchronized (hotDogs) { if (count <=0) { try { hotDogs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; System.out.println(消费者吃热狗,盘子: + count); hotDogs.notifyAll(); } } } }}
通过java实现,5个盘子,生产者不停的生产热狗,最多5个。盘子上有热狗,消费者就不停的吃热狗,直到吃完public class ProducerAndConsumer { /** *
title:main
*function:
*@author mym *@param args */ static List本文共计706个文字,预计阅读时间需要3分钟。
通过Java实现,5个盘子,生产者不断的产生热狗,最多5个。盘子上放有热狗,消费者不断的吃热狗,直到吃完。
javapublic class ProducerAndConsumer { // 盘子数量 private static final int DISHES=5; // 热狗数组,充当盘子 private static final int[] hotDogs=new int[DISHES]; // 盘子当前状态 private static int count=0;
public static void main(String[] args) { // 创建生产者和消费者线程 Thread producer=new Thread(new Producer()); Thread consumer=new Thread(new Consumer()); // 启动线程 producer.start(); consumer.start(); }
// 生产者线程 static class Producer implements Runnable { @Override public void run() { while (true) { synchronized (hotDogs) { if (count >=DISHES) { try { hotDogs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } hotDogs[count]=1; // 生产热狗 count++; System.out.println(生产者生产热狗,盘子: + count); hotDogs.notifyAll(); } } } }
// 消费者线程 static class Consumer implements Runnable { @Override public void run() { while (true) { synchronized (hotDogs) { if (count <=0) { try { hotDogs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; System.out.println(消费者吃热狗,盘子: + count); hotDogs.notifyAll(); } } } }}
通过java实现,5个盘子,生产者不停的生产热狗,最多5个。盘子上有热狗,消费者就不停的吃热狗,直到吃完public class ProducerAndConsumer { /** *
title:main
*function:
*@author mym *@param args */ static List
