Forums Register Login

output of this code

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
hi
I got the output :ABAB
+Pie Number of slices to send: Send
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
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 764 times.
Similar Threads
Thread and sleep guarantee
Simple Doubt with Threads
Java thread question...
Threads and string pool
Callin start from run method In case of threads Problem
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 18, 2024 21:29:28.