Is it wrong to do runnable.run()? - java

I am fairly new to the concept of multithreading and there is an aspect which is not clear to me.
There are two ways to create and run a thread:
Extend a Thread class and start() the thread.
Create a Runnable object, pass it to a Thread constructor and start() the thread.
And this blog post states that we always should start a thread using a start() or so was my impression of it.
But in one of the answers here you could see how a person is using runnable.run(). It gives me an impression of somewhat wrong practice.
Is it normal? Should it be avoided? You can be explicit in your answer, but any suggestions would be appreciated.

They're just different things. run() executes the Runnable in the current thread. Calling start(), on the other hand, causes the Runnable to run in the new thread.
The tutorial points it out as a pitfall. You went through all that trouble to make a thread, so if you go on to run it in the current thread instead, then it's likely a mistake.

Related

Can I start thread in Java without calling start() method?

Can I start thread in Java without calling start() method or is there any other mechanism to start a thread?
Simple answer: no.
When you check the corresponding java doc, you will find that there are many methods to deal with other aspects of threads; but start() is the only method to well, start execution of code in that different thread.
Of course you can call
someThread.run()
manually; but that will not cause that another OS thread is brought into existence to execute code in parallel.
In case you are asking "more general"; one has to understand that java.lang.Threads are regarded a very "low level" construct nowadays. We now have things like ExecutorService, Atomic variables, concurrent collections. A good starting point to read about those would be here. But is important to understand: even when using an ExecutorService; in the end, when things happen in parallel, there will be some Thread object somewhere; and start() will be called on that object at some point. No level of enclosing abstractions can make that part obsolete.
And just in case you were really asking that "how to avoid calling start()"; then you probably have an XY problem - in that case; please tell us more about the problem you intend to solve by not calling start.
You can use the ExecutorService of the Concurrency API :
Runnable yourThread = new YourThreadClass() ;
ExecutorService executorService = Executors.newSingleThreadExecutor() ;
executorService.execute(yourThread);
execytorService.shutdown();

Why does Thread implement Runnable?

A Java Thread's run() method is called by the JVM, on that thread, when the thread starts. To give a thread something to do, you can make a subclass of Thread and override its run() method, or (preferred) you can supply a Runnable to the thread's constructor. That's fine.
I was in the midst of making a subclass of Thread and overriding run, and I realized I couldn't make the method protected as I expected to because Thread.run() is public. Then I realized why: it has to be public because Thread implements Runnable. But why does it implement Runnable?
It doesn't seem logical. A thread is startable (from the current thread), but you don't run it in the same way you run() a Runnable (from the current thread); the thread runs itself (on its own thread). If you do call a Thread's run method manually, then you're not using it as a Thread, just a heavyweight Runnable.
Because of the design, any code with access to a Thread object can call its public run method and potentially poke into code that is not intended to be public or designed to be called that way. It also allows very peculiar things like this:
Thread.currentThread.run();
Is there a legitimate use for Thread implementing Runnable that I'm not seeing?
The reason is "backwards compatibility".
The Thread class originated in Java 1.0 ... or earlier. In those days, Java didn't have inner classes, and so there wasn't a light-weight way to implement a Runnable instance. If you look at old threading examples and tutorials from that era, it is common to see classes that extend Thread and override the run() method.
Over time, it was realized that extending Thread is not a good idea (for various reasons). However, the Thread design could not be changed because that would have made old Java code incompatible with newer JVMs.
Is there a legitimate use for Thread implementing Runnable that I'm not seeing?
It depends what you mean by "legitimate".
Old code that was written in the early days is not "illegitimate" by virtue of doing things the old way. There is nothing "broken" about it.
There are potentially scenarios where it does make sense to extend Thread and override the run() method. For example, you might want run() to implement some special mechanism for passing info in or out of the supplied Runnable, or implement some special exception handling, or ... make the thread "restartable".
There might even be scenarios where you'd want to call run() directly on a thread object. For instance if you were handed some "dogs breakfast" code that extended Thread and you had to convert it to run in a thread pool without modifying the original code. You might consider instantiating the crufty thread class and passing the instances as runnables to the threadpool to run. (Yes ... horrible!)
Overriding run doesn't explain why it ever needed to be public though.
If this is your issue, I think there's simple answer for that: methods implementing an interface must always be public in java. It would be possible with an abstract class for it to be protected, but if Thread were abstract, you wouldn't be able to use it as such.
As to why is Thread implementing Runnable in the first place, java must have a way of knowing at which part the thread is actually doing its job. They use run method for that. They could have more clearly separated the logic of just implementing Runnable and having Thread subclass implement that, but that is what I consider a minor mistake which is hard to change due to historical reasons.
TLDR; AFAIK there really isn't a good reason for a Thread to implement Runnable, but there is reasons for it to implement some kind of interface like that - they should've just probably had some kind of separated interface like ThreadRunnable instead of using the same Runnable interface that has other uses as well.
Note also that on modern java you should probably anyway use Callables and FutureTasks instead of Threads. "The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads.", quoting another answer here on stackoverflow.

Little confused about multi-threading concepts

I have a few questions about Java multi-threading. I am currently learning different methods of multi-threading. My first question is, what happens to the thread after the code in it is done running? Do I need to Stop/Kill the thread? I am currently making a class for each thread and implementing Runnable in each class. I then start the thread in the main class using new ThreadClass();. In the constructor of the Thread class, I have it set to make a Thread named "second." If I add new ThreadClass() twice in the main method, are both threads named "second"? Thanks.
My first question is, what happens to the thread after the code in it is done running? Do I need to Stop/Kill the thread?
The thread stops when it has nothing to do. If you have an ExecutorService, you have to use shutdown when you have finished with it.
If I add new ThreadClass() twice in the main method, are both threads named "second"?
You are making the code the same. This doesn't mean the name of the thread has to be the same (and vice-versa)
I assume you mean Thread rather than ThreadClass.
When the run method of a thread returns then the thread will stop. If you only specify the name in the second thread then only that thread will have the name "second". The first thread is unaffected.
You should avoid calling stop if at all possible as it does not allow the thread to exit cleanly.

regarding threads and runnables

I am having a problem understanding the differences between some kinds of making a tread loop.
one is (a rough demonstration):
Thread thread=new Thread("name") {
public void run()
{
// do stuff
}
}.start();
the second is:
making a class that imlpements runnable,
creating a thread :
Thread thread = new Thread(this,"name").start();
and the third (in android, i don't if it can work some how else):
making a Handler,
creating a Runnable,
and having handler.postDelayed(runnable), or handler.post(runnable).
I don't understand what's the difference, the only thing i did notice is that making a Thread makes the run loop work a lot faster than using a handler.
could some one explain to me what's the difference between them and what should i use to what?
The first and the second way are exactly the same. It is just different constructions that can be more useful in different situations. Note that Thread implements Runnable and may just run himself in the new thread.
The third way is a little bit misinterpreted by you. Handler runs Runnable in the thread where the Handler was instantiated (unless you specify another looper). If you created your Handler in the UI thread it will run Runnable in the UI thread as well. And as a result it may work slower.

General discussion about thread (Confusion)

I just want to know what is the difference between the following two methods of invoking the thread.
Please look at the two pictures of the two scenarios
My problem is that the behavior i faced is when i follow "scenario 1" i lost control of my program and the
"// other commands" in MyClass didnt run
when i followed scenario two my sequence was smooth. has anyone noticed this behavior or is it a malfunction?
Kindly give your opinions.
Regards,
I guess that instead of implementing Thread (which is not an interface as already stated) you mean to implement Runnable.
So the question seems to be (it's just a guess, since your question is missing): who should start the thread - MyClass or MyThread?
Basically, I'd prefer scenario 1 since MyThread is actually just a runnable task and should not additionally handle the thread itself.
Thus MyClass should create and start the thread. This would additionally allow you to keep references to the spawned threads and maybe call join() or other methods on them later on.
As a sidenote, I'd change MyThread into this: public class MyRunnable implements Runnable { ... }
You might want to access the Thread object, e.g. to wait for it to finish or to poll it's state. In scenario 2 you might not do this because variable t is not accessible from the client code. In order to achieve this, you either had to make t visible from the outside code or override the Thread methods (which would be a bit futile). If invokeThread is meant as some sort of convenience method, you could consider returning t.
If scenario 2 is meant as "MyThread encapsulates running a thread and controls it's state", you don't have to extend Thread (which reads a bit confusing).
As mentioned in the other comment, I would second implementing Runnable rather than subclassing Thread for cleaner code.

Categories