• Post Reply Bookmark Topic Watch Topic
  • New Topic

output of this code

 
Preetha Vasudevan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
I found this question i one of the mock exams and was not able to get the output ..

code:
class Test implements Runnable {
public void run() {
String str = new String("Hello");
synchronized(str){
try
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e){}
}
}
}
public static void main(String args[])
{
new Thread(new Test(),"A").start();
new Thread(new Test(),"B").start();
}
}
Thanks in advance.
 
Henry Wong
author
Sheriff
Posts: 22519
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by "was not able to get the output". Are you saying that you got nothing when you ran the program?

Henry
 
Preetha Vasudevan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
I got the output :ABAB
 
Henry Wong
author
Sheriff
Posts: 22519
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not sure what you are asking... so can only guess...

Are you asking "due to synchronization, why isn't the answer either AABB or BBAA"? If you are, the answer is... Because the two threads create different strings objects to use as a lock. The two threads will act independantly.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!