如上图所示,并发(concurrency)是指在一个cpu处理的线程中一直不断的切换任务,最终给人的感受就像同时执行了多个任务。而并行(parallellism)在多个cpu同一时间处理多个任务(在一个cpu中出现不了并行的状态)html
/** * 生产者生产出来的产品交给店员 */ public synchronized void produce(){ if(this.product >= MAX_PRODUCT){ try{ wait(); System.out.println("产品已满,请稍候再生产"); } catch(InterruptedException e){ e.printStackTrace(); } return; } this.product++; System.out.println("生产者生产第" + this.product + "个产品."); notifyAll(); //通知等待区的消费者能够取出产品了 }
/** * 消费者从店员取产品 */ public synchronized void consume() { if(this.product <= MIN_PRODUCT) { try { wait(); System.out.println("缺货,稍候再取"); } catch (InterruptedException e) { e.printStackTrace(); } return; } System.out.println("消费者取走了第" + this.product + "个产品."); this.product--; notifyAll(); //通知等待去的生产者能够生产产品了 }
在传统的模式中生产者和消费者在同一线程中得意实现就算线程并发(concurrency),若是生产者模式和消费者模式在不一样的线程中进行实现,就算作并行(parallellism)。
参考文档:https://www.cnblogs.com/wxd01...
图片来源:https://zhidao.baidu.com/ques...算法