Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Thread Classes

 
Raef Kandeel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raef Kandeel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the right code.



and the output is: BABCAD
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic