Refer to Q2 K&B book Chapter 9-
public class Letters extends
Thread {
private
String name;
public Letters(String name) { this.name = name; }
public void write() {
System.out.print(name);
System.out.print(name);
744 Chapter 9: Threads
}
public static void main(String[] args) {
new Letters("X").start();
new Letters("Y").start();
} }
We want to guarantee that the output can be either XXYY or YYXX, but never XYXY or any
other combination. Which of the following method definitions could be added to the Letters
class to make this guarantee? (Choose all that apply.)
A. public void run() { write(); }
B. public synchronized void run() { write(); }
C. public static synchronized void run() { write(); }
D. public void run() { synchronized(this) { write(); } }
E. public void run() { synchronized(Letters.class) { write(); } }
F. public void run() { synchronized(System.out) { write(); } }
G. public void run() { synchronized(System.out.class) { write(); } }
Answer:
E and F
I am not able to understand how can we use a class literal as the object to lock upon in the non-static synchronized block. This will be a lock on the class not on the instance so the method should be declared static in which synchronized block is placed.Please Explain.