I have a problem understanding synchronized(){} in Java. Somehow I thought that synchronized(this) I locking THIS instance of the Class and if I wanna access an attribute OR calling a function of this particular instance from another thread, than this other thread has to wait until synchronized is over. somehow in this sample code it DOESNT work. I want Thread A to wait till Thread B does something and go on later.
public class A implements Runnable{
public void start(){
Thread t = new Thread(this);
t.start();
}
public void run(){
B b = new B();
b.start();
//DO STUFF
while(b.loaded){
//WAIT FOR B DOING STUFF
}
//GO ON DOING STUFF
}
}
public class B implements Runnable {
public boolean loaded;
public B(){
loaded = false;
}
public void start(){
Thread thread = new Thread(this);
thread.start();
}
public void run(){
//DOING STUFF
synchronized (this){
loaded = true;
}
//DO OTHER STUFF
}
}
It works if I do a method called,
public synchronized boolean getLoaded(){return loaded;}
But why do the writing AND reading process have to be synchronized ? Shouldn't it be enough if the object is only locked while writing cause then the reading has to wait anyways? in the first example I expect the programming doing the following stuff:
Thread A is reading loaded variable.
Thread B wants to write loaded variable but its synchronized so it locks the object.
Thread A tries to read loaded variable but the object is locked so it waits.
Thread B writes the variable.
Thread B unlocks.
Thread A keeps reading.
I read a lot about this topic but I couldn't understand it like 100%. Wish someone could explain that simple project to me.