Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scjp self test on thread doubt

 
Abhishek Mantri
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2. Given:
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:
E and F are correct.

Can any body explain how F. is correct?
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
-Ben
 
Abhishek Mantri
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Abhishek Mantri
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Evan !
 
Abhishek Mantri
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ivan !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic