The following thread is made to run unpredictably. Sometimes it may print ABC and others 123. I don't get why it's able to print ABC. Please explain its flow of execution.
public class ArrayDeclaration implements Runnable {
String [] s;
public ArrayDeclaration (String []s){
this.s=s;
}
public void run() {
synchronized (this){
try
{
wait(5000);
System.out.print(s[0]+s[1]+s[2]);
}
catch(InterruptedException ie){
}
}
}
}
/**
* @param args the command line arguments
*/class Test{
public static void main(String[]args)throws Exception {
String[] s = new String []{"1","2","3"};
ArrayDeclaration myRunnable = new ArrayDeclaration(s);
// TODO code application logic here
Thread t1 = new Thread(myRunnable);
t1.start();
t1.join(5000);
s[0]="A";
s[1]="B";
s[2]="C";
}
}
I don't get the scope of the String array. Why is it (sometimes) changed to ABC and printed? Shouldn't the changes just affect its scope within main? Does this behavior has something to do with the String pool?