GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner Thread Classes 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 "Inner Thread Classes" Watch "Inner Thread Classes" New topic
Author

Inner Thread Classes

Raef Kandeel
Ranch Hand

Joined: Aug 05, 2007
Posts: 87
public class SyncTest {
public static void main (String [] args) {
final StringBuffer s1 = new StringBuffer ();
final StringBuffer s2 = new StringBuffer ();
new Thread () {
public void run() {
synchronized (s1) {
s2.append (�A�);
synchronized (s2) {
s1.append (�B�);
System.out.println (s1);
System.out.println (s2);
}
}
}
}.start();
public void run() {
synchronized (s2) {
s2.append (�C�);
synchronized (s1) {
s1.append (�D�);
System.out.print (s2);
System.out.print (s1);
}
}
}.start ();
}
}

I tried this program and the output was BAACBD. I tried it on both Windows and Linux . I removed the synchronized �methods� and tried again and it gave me the same output. Are these threads concurrent?


SCJP, SCWCD
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy, Raef!

I guess you won't get much answers to this question because the code is unreadable and cannot compile.

Perhaps repost the code in a repaired version and use code tags.
At the posting page, mark the part of your posting that should be indented. Usually that will be your code (or some tabellaric output).

Hit the - Button below.
that's it!



and:
you wrote:

I removed the synchronized “methods” and tried again


Do you mean, you removed the synchronized keyword and tried again?

If so, you cannot always expect a change in behaviour, as the code in the run method is so short and performed so quickly, that even in a non-synch method no other thread has the chance to get selected by the scheduler.
Perhaps try to insert an additional call to yield() in that method.


Yours,
Bu.


all events occur in real time
Raef Kandeel
Ranch Hand

Joined: Aug 05, 2007
Posts: 87


Thanks a lot for all your responses. And you are right it didn't compile. And I mean synchronized keywords instead of methods.
Raef Kandeel
Ranch Hand

Joined: Aug 05, 2007
Posts: 87
This is the right code.



and the output is: BABCAD
Deepak Jain
Ranch Hand

Joined: Aug 05, 2006
Posts: 637
Hi Raef,
Could you please have a look at

Javaranch

We had a full length discussion on the same example and the issues with this class.
If you do not understand the explaination, please feel free to ask your questions.
Thanks
Deepak
[ August 07, 2007: Message edited by: Deepak ]

SCJP, SCWCD, SCBCD
 
GeeCON Prague 2014
 
subject: Inner Thread Classes