问题描述
packagecom.http;publicclasstest2{publicstaticvoidmain(String[]args)throwsInterruptedException{modem=newmode();shengs=newsheng(m);xiaox=newxiao(m);Threadt1=newThread(s);Threadt2=newThread(s);Threadt5=newThread(s);Threadt3=newThread(x);Threadt4=newThread(x);Threadt6=newThread(x);t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();}}classxiaoimplementsRunnable{privatemodem;publicxiao(modem){this.m=m;}@Overridepublicvoidrun(){while(true){try{m.get();}catch(InterruptedExceptione){e.printStackTrace();}}}}classshengimplementsRunnable{privatemodem;publicsheng(modem){this.m=m;}@Overridepublicvoidrun(){while(true){try{m.set("蛋糕");}catch(InterruptedExceptione){e.printStackTrace();}}}}classmode{privateStringname;privatebooleanflag;publicsynchronizedvoidset(Stringname)throwsInterruptedException{if(flag)//whilewait();if(!flag){//改while时去除this.name=name;System.out.println(Thread.currentThread().getName()+"生产了"+name);flag=true;}notify();//notifyAll();}publicsynchronizedvoidget()throwsInterruptedException{if(!flag)//whilewait();if(flag){//改while时去除System.out.println(Thread.currentThread().getName()+"消费了"+name);flag=false;}notify();//notifyAll();}}
解决方案
本帖最后由 DaoDivDiFang 于 2014-10-15 12:31:35 编辑
解决方案二:
请问这里我不用while(flag)判断标记,也不用notifyAll();唤醒所有进程。就以上的代码有没有问题?解决了多线程的通信问题没有?