I got this from master exam by K & B.
In the folllowing code:
public cass SyncTest {
private static Foo foo=new Foo();
static class Increaser extends
Thread {
public void run() {
foo.increase(2);
}
}
public static void main(
String args[]) {
new Increaser().start();
new Increaser().start();
new Increaser().start();
}
}
class Foo {
private int data=23;
public void increase(int amt) {
data =data+amt;
System.out.println("Data is: " +data);
}
}
Assuming that data must be protected from corruption, what can you add to the preceding code to ensure the integrity of data ?
A. Synchrnize the run method.
B. Wrap the synchronize(this) around the call to f.increase();
C. The existing code will not compile.
D. The existing code will cause a runtime exception.
E. put in a wait call prior to invoking the increase method.
F. Sysnchronize the increase method.
Answer is F.
Here why option A and B are wrong? They also seems to be correct to me.
Thanks,
Geeta Vemula.