多线程——等待唤醒机制经典实例:生产者消费者模式(优化)

来源:互联网 发布:混迹知乎的浩天哥 编辑:程序博客网 时间:2024/04/30 04:35
package com.work.wor01;/** * 等待唤醒机制经典实例:生产者消费者模式。 *  * 当使用多个生成者线程,多个消费者线程时,会出现线程不安全的现象,即使是同步了,也不管用。 *  * 发生的问题: * 生产者生产的商品没有被消费,就生成了新的商品。 *  * 线程不安全现象产生的原因:1.本方唤醒了本方2.被唤醒的本方没有判断标记。解决结论:无论哪个线程被唤醒,都一定要判断标记。解决方案:把if改成while即可。出现了新的问题,所有的线程都在等待,程序死锁了,怎么办?分析:本方唤醒了本方,没有唤醒对方。解决方案:一定要唤醒对象,没有直接唤醒对方的方法,所以唤醒所有线程。 * *///资源类class Resource1{private String name;private int count = 1;boolean flag;public synchronized void set(String name){while(flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.name = name+count;count++;System.out.println(Thread.currentThread().getName()+"..生产了.."+this.name);flag=true;this.notifyAll();}public synchronized void get(){while(!flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println(Thread.currentThread().getName()+"..消费了.."+this.name);flag = false;this.notifyAll();}}//生产类class Produce implements Runnable{Resource1 r;public Produce(Resource1 r) {super();this.r = r;}@Overridepublic void run() {while(true){r.set("馒头");}}}//消费类class Customer1 implements Runnable{Resource1 r;public Customer1(Resource1 r) {super();this.r = r;}@Overridepublic void run() {while(true){r.get();}}}public class ProCuswork01 {public static void main(String[] args) {Resource1 r = new Resource1();Produce p = new Produce(r);Customer1 c = new Customer1(r);Thread t1 = new Thread(p);Thread t2 = new Thread(c);Thread t3 = new Thread(p);Thread t4 = new Thread(c);t1.start();t2.start();t3.start();t4.start();}}

0 0
原创粉丝点击