multithreading - How does notify work in Java threads? -
i new using threads in java . have simple reader writer problem when writer comes in on thread, reader wait writer complete.
however, when run program, find thread doesn't notified? why this?
my code below:
public class readerwriter { object o = new object(); volatile boolean writing; thread readerthread = new thread( "reader") { public void run() { while(true) { system.out.println("reader starts"); if(writing) { synchronized (o) { try { o.wait(); system.out.println("awaked wait"); } catch (interruptedexception e) { e.printstacktrace(); } } } system.out.println( "reader thread working "+o.hashcode()); } } }; thread writerthread = new thread("writer" ) { public void run() { system.out.println( " writer thread"); try { synchronized (o) { writing = true; system.out.println("writer working .. "); thread.sleep(10000); writing = false; o.notify(); system.out.println("reader notified"); } } catch (interruptedexception e) { e.printstacktrace(); } } }; public static void main(string[] args) { readerwriter rw=new readerwriter(); rw.readerthread.start(); rw.writerthread.start(); }
}
here problem synchronized (o)
function.
the synchronized function makes thread synchronized , there execute 1 thread @ time object
o
. hence while value ofwriting
true. wont allow 2nd treadreaderthread
execute duesynchronized (o)
inreaderthread
you getting infinite loop because there no terminate statement.
here know when thread terminates
look @ code know more synchronized function
synchronized(object) { // statements synchronized }
here, object reference object being synchronized. synchronized block ensures call method member of object occurs after current thread has entered object's monitor
.
read check notify methods
the object class in javasw has 3 final methods allow threads communicate locked status of resource. these methods wait(), notify(), , notifyall(). thread obtains lock particular resource via synchronized block instance of resource. suppose thread requires thread perform action on resource before acts on resource. thread can synchronize on resource , call wait() method on resource. this says thread wait until has been notified can proceed act.
the wait() method can take optional timeout value parameter. if value used, means thread either wait until it's notified or continue execute once timeout value has passed.
if thread required perform task on resource before thread operates on resource (and other thread waiting via wait()
method on resource), thread needs synchronize on resource. can perform actions on resource.
in order notify waiting thread once these actions have completed, notify()
method on resource called. notifies waiting thread can proceed act. if multiple threads waiting resource, there no guarantee thread given access resource. if desired waiting threads awoken, notifyall()
method can called on resource.
Comments
Post a Comment