jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question" Watch "Question" New topic
Author

Question

Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

public class MyTest
{
private int x;
public void fun()
{
int current = x;
x = current + 1;
}

public void go()
{
for(int i = 0; i < 5; i++)
{
new Thread() {
public void run()
{
fun();
System.out.print(x + ", ");
}
}.start();
}
}

This Question asks that what changes would you do in in order to guarantee 1,2,3,4,5, output

But according to me this program is always give 12345.....Please solve my misunderstanding here ??


OCJP-90%,OCPWCD-95%
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3056
    
  33

Please QuoteYourSources and UseCodeTags


Mohamed Sanaulla | My Blog
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

actually my friend gave asked me this question....so i don't know the source.......Please Help Friends.....i am sick of this Thread thing
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Mohamed Sanaulla wrote:... UseCodeTags


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hmm, what happened when you add Thread.sleep(1) as a last statement in public void fun() ?
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Seetharaman Venkatasamy wrote:Hmm, what happened when you add Thread.sleep(1) as a last statement in public void fun() ?



Thanks......But how come i couldn't notice that .....

Thanks Any Ways !!!
Suhrid Karthik
Ranch Hand

Joined: Aug 31, 2008
Posts: 58

Sagar Shroff wrote:
Seetharaman Venkatasamy wrote:Hmm, what happened when you add Thread.sleep(1) as a last statement in public void fun() ?



Thanks......But how come i couldn't notice that .....

Thanks Any Ways !!!


Adding Thread.sleep() will not answer your question. Have you figured it out yet ?
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Suhrid Karthik wrote:

Adding Thread.sleep() will not answer your question. Have you figured it out yet ?


Yes ,Actually as i posted earlier i thought that the output was always guaranteed to be 1,2,3,4,5 and also the compiler was giving me the same ,which is actually not guaranteed to give me the same every time even though there is less possibility because the fun() was not synchronized so there was always a possibility that multiple threads would manipulate the x. That i realized when Seetharaman asked me to try out a sleep.

But still 1 question arises is that in the below code:


As you can see i have added synchronized keyword and the System.out.println() is moved to the fun () .........Now 1 question arises is that synchronize would always allow access to the method if threads are running with different object.Which is not happening here Right ?? ??.....So i decided to remove synchronized keyword from the fun() but then the output is something like this : 5,5,5,5,5,
Why is it behaving like this as if the Threads are running on the same object !!!
Eoin Brosnan
Ranch Hand

Joined: Dec 12, 2009
Posts: 37


I think that is the correct answer, but understanding it is what is important. First of all you need to know why they the code doesn't work as required. Try and figure that out and then the answer will make sense.

edit: It seems you came up with a similar answer.

If you remove the synchronized from fun() then it won't always print 5,5,5,5,5 but it will a lot of the time. With synchronized you are getting the lock on the MyTest() object that you create in main. This means that once 1 of your threads have called MyTest().fun() that no other thread can enter the method until the first one is finished.

However if you removed the synchronized then threads can swap in and out and enter fun() at any stage, no matter if other threads are also in there. As you are putting your thread to sleep for 1 millisecond(a long time in computer time!) then the thread will most likely exit during sleep, and right before you print(x). This means that usually all 5 threads will increment the value x to 5 BEFORE any of them print, hence why you get 5,5,5,5,5.

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

hmm. now just remove the Thread.sleep .i.e, just put empty try catch there and see the difference
Suhrid Karthik
Ranch Hand

Joined: Aug 31, 2008
Posts: 58

Sagar Shroff wrote:
As you can see i have added synchronized keyword and the System.out.println() is moved to the fun () .........Now 1 question arises is that synchronize would always allow access to the method if threads are running with different object.Which is not happening here Right ?? ??.....So i decided to remove synchronized keyword from the fun() but then the output is something like this : 5,5,5,5,5,
Why is it behaving like this as if the Threads are running on the same object !!!


The different threads are in fact using the same object of the Test1 class (the object which you created using new Test1() in the main method ) to invoke the fun method. This is why you need the synchronized keyword to prevent the multiple threads from accessing the shared variable x concurrently. So if you remove the synchronized keyword, the behavior you described (printing 5,5,5..) can occur.
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Seetharaman Venkatasamy wrote:hmm. now just remove the Thread.sleep .i.e, just put empty try catch there and see the difference


There is no difference...and what's the use of empty try catch .....??...I didn't got what you are trying to tell ??......
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Eoin Brosnan wrote:

I think that is the correct answer, but understanding it is what is important. First of all you need to know why they the code doesn't work as required. Try and figure that out and then the answer will make sense.

edit: It seems you came up with a similar answer.

If you remove the synchronized from fun() then it won't always print 5,5,5,5,5 but it will a lot of the time. With synchronized you are getting the lock on the MyTest() object that you create in main. This means that once 1 of your threads have called MyTest().fun() that no other thread can enter the method until the first one is finished.

However if you removed the synchronized then threads can swap in and out and enter fun() at any stage, no matter if other threads are also in there. As you are putting your thread to sleep for 1 millisecond(a long time in computer time!) then the thread will most likely exit during sleep, and right before you print(x). This means that usually all 5 threads will increment the value x to 5 BEFORE any of them print, hence why you get 5,5,5,5,5.



Thanks for your detailed description !!
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Suhrid Karthik wrote:
Sagar Shroff wrote:
As you can see i have added synchronized keyword and the System.out.println() is moved to the fun () .........Now 1 question arises is that synchronize would always allow access to the method if threads are running with different object.Which is not happening here Right ?? ??.....So i decided to remove synchronized keyword from the fun() but then the output is something like this : 5,5,5,5,5,
Why is it behaving like this as if the Threads are running on the same object !!!


The different threads are in fact using the same object of the Test1 class (the object which you created using new Test1() in the main method ) to invoke the fun method. This is why you need the synchronized keyword to prevent the multiple threads from accessing the shared variable x concurrently. So if you remove the synchronized keyword, the behavior you described (printing 5,5,5..) can occur.


Thank you Suhrid !!...Thats what i didn't noticed ...Thank You !!
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Sagar Shroff wrote:
Seetharaman Venkatasamy wrote:hmm. now just remove the Thread.sleep .i.e, just put empty try catch there and see the difference

There is no difference...and what's the use of empty try catch .....??...I didn't got what you are trying to tell ??......


well, actually the empty try{}catch(Exception e){} idiom slow the execution , it might be less time than Thread.sleep(1) . I thought of you may be see the difference well. just run couple of times
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

1 more Question relating Thread is that.When i call something like this,consider Test is a class that extends Thread...

Test t=new Test();
Thread t=new Thread(t);
then when i call t.start(); why does it call run method of Test class.
Now the rule is that overrided method gets called when your object is of Subclass Type.Then why so in Threads ???

Can some one also mention the situations where the run method of Thread class is called ..Please give me some code examples
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

when you say start on thread instance(say T) then Thread class run method invoked and there it calls the run method of the runnable type object which you passed in Thread constructor while you created the Thread instance(T).
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Sagar Shroff wrote:1 more Question relating Thread is that.When i call something like this,consider Test is a class that extends Thread...

Test t=new Test();
Thread t=new Thread(t);
then when i call t.start(); why does it call run method of Test class.
Now the rule is that overrided method gets called when your object is of Subclass Type.Then why so in Threads ???

Can some one also mention the situations where the run method of Thread class is called ..Please give me some code examples


I think i have the got the answer so please correct me if i am wrong.
When i do something like this

it calls the run of Thread class and not the overrided one.
But when i called the overloaded constructor of Thread i.e when i pass certain object like this

This calls the overrided run method.
Please correct me if i am having some wrong Concepts here ??
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

start a new thread for a new question. so that you can attract the people by your new subject line to get more response
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

you are right. do you have source code for java.lang.Thread class? if yes just see the Thread#run method!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question
 
Similar Threads
Thread Output
Thread Safe Code
instance initializer