Hey javaranchers,
given this code, which one statement is true:
public class Myclass extends Thread{
static Object lock1 = new Object();
static Object lock2 = new Object();
static volatile int i1,i2,j1,j2,k1,k2;
public void run(){while(true) {doit(); check();}}
void doit(){
synchronized(lock1){i1++;} //1
j1++;
synchronized(lock2){k1++; k2++;} //2
j2++;
synchronized(lock1){i2++;} //3
}
void check(){
if (i1 != i2) System.out.println("i");
if (j1 != j2) System.out.println("j");
if (k1 != k2) System.out.println("k");
}
public static void main(
String args[]){
new MyClass().start();//Thread A
new MyClass().start();//Thread B
}
}
a) The program will fail to compile
b) One can't be certain whether any of the letters i,j, and k will be printed during execution
c) One can be certain that i,j,k won't be printed during execution
d) One can be certain that i,k will never be printed during execution
e) One can be certain that k will never be printed during execution
my answer was c, however the right answer is b.
Does this mean that if
Thread A gets to 1 first,
Thread B can go ahead and execute 2 or 3(and not wait in 1)
then return to 1 later
Thanks