Hello Everybody,
I'm facing one problem in below code from K&B
Thread exercise Ques No. 2
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);
}
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:
� 3 E and F are correct. E and F both cause both threads to lock on the same object, which will
prevent the threads from running simultaneously, and guarantee XXYY or YYXX. It's a bit
unusual to lock on an object like System.out, but it's perfectly legal, and both threads are
locking on the same object.
�˚ A can't guarantee anything since it has no synchronization. B and D both synchronize on
an instance of the Letters class�but since there are two different instances in the main()
method, the two threads do not block each other and may run simultaneously, resulting in
output like XYXY. C won't compile because it tries to override run() with a static method,
and also calls a non-static method from a static method. G won't compile because
System.out.class is nonsense. A class literal must start with a class name. System.out is
a field not a class, so System.out.class is not a valid class literal.
In the above code I'm not able to understand that how we can restrict output to XXYY by synchronizing through System.out
Regards
Manju