Android : Understanding multithreading in Java

on Friday, March 20, 2015


I'm trying to understand a Java example (in Android), where there is a Thread, named ConnectedThread, taht has a run method like this:



public void run(){
while(true){
//do some work
}
}


The thread has also the following method:



public void write(byte[] buffer){
try{
mmOutStream.write(buffer);
}catch(IOException e){}
}


When the run() method is executed, I guess that no other method can run inside the thread. So the method write() should not be execute (until the loop ends), if someone call it. But it seems I'm wrong, since my example calls that method in this way (from another thread):



public void write(byte[] out){
//create temporary object
ConnectedThread r;
//synchronize a copy of the ConnectedThread
synchronized(this){
r = mConnectedThread; // mConnectedThread is the Thread already running
}
r.write(out);
}


Can someone explain me what is happening here? And why is required to synchronize (using the keyword synchronized a copy of the original thread?


0 comments:

Post a Comment