I tried overloading run() inside an implementer of Runnable. But how do i make a thread call an overloaded version of run() ? One way would be to call the overloaded version from within run() OR create another Runnable implementer . Any other ways ? Is this overloading of any use in real-world apps? . Can i put this in the Threads sub-forum ? Here is the code that uses Runnable :
By extending Thread class : Both versions of thread run here. I want to run only the String version. How to do it ?
Invoking the start method will spawn a new Thread and it will in turn invoke the run() method. If you invoke the run() or an overloaded version of run() - Its just like invoking anyother method in the instance. If you want to invoke the overloaded version of run() i.e the run(String) you can do it in the run() method body.
And you just cant run the overloaded, because Thread class is designed in such a way that it will invoke the run() method by default. So I dont think you can make it to invoke the run(String).
By the way I like the way you have been trying out different concepts in code.
Yes, but it won't be run in a separate thread. If you want to do this, you should create a Runnable subclass, with a constructor that takes the parameters you actually wanted to pass to the run method, and store the arguments in some fields. Then the run method can operate on those fields.
I was checking the forum to check the solutions for this excercise. I got the expected result but is there any need to make some fields final as given above? I am quite new to Threads so please help me out. Is this solution ok?
Stephan van Hulst
Joined: Sep 20, 2010
No, sadly this solution is not fine. First of all, you're extending Thread. Never extend Thread. Implement Runnable or Callable instead.
Secondly, you're using static fields to hold data only one specific instance is supposed to work on. Don't make it static.
You are also synchronizing on a non-final field. The value of this.b can change while one thread is still executing inside the synchronized block. This effectively makes your synchronized block useless, because another thread can just enter the block after changing the value of this.b.
Actually, if you didn't use static fields, you wouldn't need a synchronized block in the first place, because your instances wouldn't be sharing data.