Synchronization

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

[1431 byte] By [deepthi_tirunaharirama] at [2007-11-26 21:41:01]
# 1
Because with B, each instance of the Letters class will be syncing on a different object--itself. Syncing only blocks threads that are waiting on the same object's monitor.In E and F, all threads sync on the same object.
jverda at 2007-7-10 3:26:07 > top of Java-index,Core,Core APIs...
# 2
In synchronization thread are contesting with each other to acquire the lock over some shared resource (and only one thread can acquire the lock)In case of B the object is not shared among the running threads.Hope it is clear to you :)
sanborsea at 2007-7-10 3:26:07 > top of Java-index,Core,Core APIs...
# 3
If you are new to threading and don't understand the concept of synchronization then check out some of the resources listed in the FAQ and do some reading.This looks like a homework question to me.
davidholmesa at 2007-7-10 3:26:07 > top of Java-index,Core,Core APIs...
# 4
couldn't you rewrite the write function to be synchronised and make it static as well. would that solve the problem.
KeyzerSuzea at 2007-7-10 3:26:07 > top of Java-index,Core,Core APIs...