java multithreading problem -
below part of code. confused why "notify 1" can not wake function waiting.
it seams have with: when 1 thread executing synchronized method object, other threads invoke synchronized methods same object block (suspend execution) until first thread done object.
why result not: wait, notify1, wait finish, notify2, . . .
instead is: wait, notify1, notify2, notify2, . . . notify2, notify 2, notify 3, wait finish, skip wait, skip wait, skip wait, . . .
code { . . .
multithreadcontent m; void dividetoparts(file testfile,fileinputstream fileinputstream, object hashmachine) throws ioexception, interruptedexception{ . . . //run here m = new multithreadcontent(fileinputstream,(int)temp23,(int) (testfile.length()%temp23), numberofparts, hashmachine); new thread(new read()).start(); m.update(); } class read implements runnable{ @override public void run() { try { m.read(); } catch (interruptedexception e) { e.printstacktrace(); } } } class multithreadcontent{ . . . boolean prenotready=true; boolean updatenotfinished; //read{ public synchronized void read() throws interruptedexception{ //initial{ readnextblock(); preblock=nextblock; read_notify(); system.out.println("notify 1");//d if(finishedread!=true) { readnextblock(); read_wait(); } else return; //} while(finishedread!=true){ preblock=nextblock; read_notify(); system.out.println("notify 2");//d readnextblock(); read_wait(); } //closing{ preblock=nextblock; read_notify(); system.out.println("notify 3");//d //} } void read_notify(){ prenotready=false; notifyall(); } void read_wait() throws interruptedexception{ if(updatenotfinished==true) { wait(); system.out.println("wait update");//d } prenotready=true; } //} //update{ public synchronized void update() throws interruptedexception{ (int = 0; < totalparts; i++) { update_wait(); dividetoparts_update(hashmachine, preblock); update_notify(); } } void update_notify(){ updatenotfinished=false; notifyall(); } void update_wait() throws interruptedexception{ if(prenotready){ system.out.println("wait");//d wait(); system.out.println("wait finish");//d } updatenotfinished=true; system.out.println("skip wait");//d } //} } }
the reason because have not left synchronized block. read_wait method never enters if block because updatenotfinished default initialized false. since read_wait never enters if block continue loop on finishedread!=true. until method , synchronized block exited never give hold of monitor.
once complete lock available , other thread awaken correctly.
to test talking about, try setting updatenotfinished = true on initialization.
Comments
Post a Comment