Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Synchronization

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Everyone

I am new to threads and having a problem understanding the concept of Synchronization.

I am providing the code below:

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(); } }


The correct answers for this question are E and F.
But i was wondering why option B also cannot be the right answer for this question.

Can anybody explain...

Thanks in advance

With regards
Deepthi
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because (B) synchronises on the instance of Thread. The two threads have different instances of Thread, so the synchronisation does not prevent them running simultaneously.
 
Bartender
Posts: 1638
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Option B is not correct because that will hold an instance level lock and since both the threads are different instances, none of them will wait for the other.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic