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 is E and F. Can any one explain me for answer E ? Thanks !!!
Choice E: public void run() {synchronized (Letters.class) { write();} }
By saying synchronised(Letters.class) you are getting the lock of the class Letters (Remember there is one and only 1 lock for any class)
So when you say new Letters("X").start(); The above run() method will be automaticall invoked, and obtain the lock of class "Letters" and this thread will only release the lock after completing the write() method, which guarantees printing XX or YY depending on the thread invoking, but never XY.
Originally posted by priti manas duddilla: Choice E: public void run() {synchronized (Letters.class) { write();} }
By saying synchronised(Letters.class) you are getting the lock of the class Letters (Remember there is one and only 1 lock for any class)
So when you say new Letters("X").start(); The above run() method will be automaticall invoked, and obtain the lock of class "Letters" and this thread will only release the lock after completing the write() method, which guarantees printing XX or YY depending on the thread invoking, but never XY.
Hi guys !!! By "each object has just one lock" i understand : any instance of an object has just one lock.[Correct me if i'am wrong]. And per my understand for class litteral, When i write Letters.class the compiler will find the instance that represents the class called Letters.
I think my problem is with synchronising on class literal. How does it work ? Thanks.
I got it !!!. I was misunderstanding the String literal's concept. I find this on the Sun's site:
There is one Class object for each loaded class known to the Java runtime system.
The output will be the same. And it refer to the same object.
And returning to my doubt: when i write public void run() {synchronized (Letters.class) { write();} I will get the lock for the class litteral which is the same for new Letters("X") and new Letters("Y").