File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes scjp self test on thread doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "scjp self test on thread doubt" Watch "scjp self test on thread doubt" New topic

scjp self test on thread doubt

Abhishek Mantri

Joined: Sep 06, 2007
Posts: 25
2. Given:
public class Letters extends Thread {
private String name;
public Letters(String name) { = name; }
public void write() {
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(); } }
E and F are correct.

Can any body explain how F. is correct?
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

Abhishek Mantri,

It is important that you
QuoteYourSources when posting mock questions to JavaRanch. Please go back and and add one to each of these questions. Any mock questions with out a valid source need to be removed.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Abhishek Mantri

Joined: Sep 06, 2007
Posts: 25
Sorry Ben
The source is self test on threads from SCJP book by Kathy.
since this has become a universal book i forgotto mention,sorry again !
Ivan Ivanic
Ranch Hand

Joined: Oct 31, 2007
Posts: 100
when one thread get lock on System.out object it will execute its entire method write(). which is to print two times letter.
if other thread tries to use System.out i.e. to write some chars to standard output it has to wait until lock of System.out is released.

<a href="" target="_blank" rel="nofollow">Use Real Words</a> <a href="" target="_blank" rel="nofollow">!!!Use Code Tags!!!</a> <a href="" target="_blank" rel="nofollow">Say Thanks</a><br />scjp6
Abhishek Mantri

Joined: Sep 06, 2007
Posts: 25
Thanks Evan !
Abhishek Mantri

Joined: Sep 06, 2007
Posts: 25
Thanks Ivan !
I agree. Here's the link:
subject: scjp self test on thread doubt
It's not a secret anymore!