这是个读者写者程序~publicclassMain{Factoryfa=newFactory();//主程序publicstaticvoidmain(String[]args){Mainmm=newMain();Writerwriter=mm.newWriter();newThread(writer).start();newThread(writer).start();newThread(mm.newReader()).start();}//写者classWriterimplementsRunnable{intmax=1000;//总共写1000次inti=0;@Overridepublicvoidrun(){while(true&&ifa.writeSomething(); ++i;}}}//读者classReaderimplementsRunnable{@Overridepublicvoidrun(){while(true){fa.readSomething();}}}classFactory{Listrepo=newArrayList ();//仓库 intmax=100,min=0,isn=0;//仓库最大值、最小值、图书编号//写publicsynchronizedvoidwriteSomething(){if(repo.size()==max){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}System.out.println(Thread.currentThread().getName()+"-write:"+isn+"/Size:"+repo.size());repo.add(newInteger(isn++));this.notify();}//读publicsynchronizedvoidreadSomething(){if(repo.size()==min){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}System.out.println(Thread.currentThread().getName()+"-read:"+repo.get(0));repo.remove(0);this.notifyAll();}}}一个写者,多个读者的时候这个程序是没问题的多个写者,一个读者的时候就出问题了,问题在与,仓库最大容量为100,这种情况下会超过100,我感觉问题出在多个写者会相互唤醒,不知道我分析的对不对,所以改了一下writeSomething(),如下://写publicsynchronizedvoidwriteSomething(){if(repo.size()>=max){try{this.wait();}catch(InterruptedExceptione){e.printStackTrace();}}else{System.out.println(Thread.currentThread().getName()+"-write:"+isn+"/Size:"+repo.size());repo.add(newInteger(isn++));this.notify();}}这样的确不会出现容量超过100的情况了,但是会死锁,执行不完,,彻底晕了,求解救~~
桃花长相依
Qyouu
相关分类