胶多不粘话多不甜,直接上代码:
生产者类:
/** * Created by 51304 on 2016/2/28. */ public class P { private String lock; public P(String lock){ this.lock = lock; } public void setValue(){ try{ synchronized (this.lock){ if(!ValueObject.value.equals("")){ lock.wait(); } String value = System.currentTimeMillis() + "_" + System.nanoTime(); System.out.println("set value is " + value); ValueObject.value = value; lock.notify(); } } catch (InterruptedException e){ e.printStackTrace(); } } }
消费者类:
import com.sun.org.apache.xpath.internal.SourceTree; /** * Created by 51304 on 2016/2/28. */ public class C { private String lock; public C(String lock){ this.lock = lock; } public void getValue(){ try{ synchronized (this.lock){ if(ValueObject.value.equals("")){ this.lock.wait(); } System.out.println("get value is " + ValueObject.value); ValueObject.value = ""; this.lock.notify(); } } catch (InterruptedException e){ e.printStackTrace(); } } }
存储值的对象:
/** * Created by 51304 on 2016/2/28. */ public class ValueObject { public static String value = ""; }
生产者线程:
/** * Created by 51304 on 2016/2/28. */ public class ThreadP extends Thread { private P p; public ThreadP(P p){ this.p = p; } @Override public void run(){ while (true){ p.setValue(); } } }
消费者线程:
/** * Created by 51304 on 2016/2/28. */ public class ThreadC extends Thread { private C c; public ThreadC(C c){ this.c = c; } @Override public void run(){ while (true){ c.getValue(); } } }
main方法:
/** * Created by 51304 on 2016/2/28. */ public class TestMain { public static void main(String[] args) { String lock = new String(""); P p = new P(lock); C c = new C(lock); ThreadP threadP =new ThreadP(p); ThreadC threadC = new ThreadC(c); threadP.start(); threadC.start(); } }
运行截图:
思考:如果多生产者和多消费者程序能正常工作吗?
答案是:程序会出现假死,也就是所有线程都停留在等待状态。出现这个现象的原因是,多生产者模式下notify()通知的线程还是生产者(选择通知那个线程时随机的,但只会通知一个),同理消费者也一样。当然解决的办法很明显使用notifyall().