203k views
25 votes
Need help pls public class TestThread extends Thread {

private static int x;
public synchronized void doSomething () {
int current = x;
current++;
x = current;
}
public void run() {
doSomething();
}
}

Which statement is
true?
Select one:

a. Declaring the doSomething() method as static would make the class thread-safe

b. Synchronizing the run() method would make the class thread-safe

C. The data in variable "X" are protected from concurrent access problems

d. Compilation fails
e. An exception is thrown at runtime​

User Erivan
by
3.6k points

1 Answer

1 vote

Answer:

a.

Step-by-step explanation:

The private variable x is static, so synchronizing on object instances doesn't add any real protection.

If multiple objects of the class exist, they can still simultaneously run doSomething() and mess up the shared x.

By making doSomething() static, there is only one instance of it and indeed access to x would become thread safe.

User Saurabh Ariyan
by
4.5k points