Why do we need a Runnable to start threads? - java

Why we need to pass the runnable instance while creating the threads using the Runnable interface?

The reason we need to pass the runnable object to the thread object's constructor is that the thread must have some way to get to the run() method we want the thread to execute.
Take an e.g
public class CustomApplet extends Applet {
public void init() {
Runnable ot = new OurClass();
Thread th = new Thread(ot);
th.start();
}
}
Since we are no longer
overriding the run() method of the Thread class, the default run() method of the Thread class is
executed; this default run() method looks like this
public void run() {
if (ot!= null) {
ot.run();
}
}
Hence, ot is the runnable object we passed to the thread's constructor. So the thread begins execution with the run() method of the Thread class, which immediately calls the run() method of our runnable object.

What do you want the new thread to do? You probably want it to execute some code. But what code must it run? You can't just put code in a thread. And Java does not have function pointers. A little trick to solve that problem is to use a object that implements a function. That function is run. So, the object must have a run method. That is what the Runnable interface does, assure it has a run method. Thus, if we give a Runnable object, the thread knows what to do!

Related

Java Multithreading : how does thread creation with Runnable interface work?

Could someone explain what does this code does? new Thread(new X()).start();
Rest of the code:
class X implements Runnable {
X() {}
}
public static void main(String[] arg) {
new Thread(new X()).start();
}
}
This is a very simple example, which shows how to create a new thread and run it. When you create new threads in Java, you give them something to do - a "Runnable".
class X implements Runnable
This interface has only one method - run(). So you create a new thread, with a runnable in its' constructor.
new Thread(new X())
Once you have created a new thread, you have to start it with the start() method. This is when it calls the runnable's run() method. In your example, this has just been chained on after the construction of the thread:
new Thread(new X()).start();
Now, this example is unusual in that class X doesn't actually implement the run method. But normally, there's that extra bit, so your example would look like this:
class X implements Runnable {
public void run() {
System.out.println("This is running on a different thread!");
}
public static void main(String[] arg) {
new Thread(new X()).start();
}
}
You don't need to define a constructor if it's blank, first of all. It'll automatically be blank if you don't define one. Second of all, you can simply do an anonymous class definition, which I'll explain in a second. The method isn't main in this case, it's run. You can define a thread object using the anonymous class definition, too.
new Thread() {
#Override
public void run() {
//Code here
}
}.start();
The anonymous class definition allows you to define and instantiate a class which extends/implements another class both at the same time without actually creating the class. Also, note that X.main() is static, meaning that any instance of X will not have that method. You want to override run and call start. Start is just a method which calls run in a different thread. Note that you can't start a thread twice.
Every thread object has a method run(). if you call the start() method of thread object, then it will execute run().
The only difference is it will be executed separately/parallely and won't be in the existing sequence of operation.
You can create thread in two ways : one by extending Thread and other by implementing Runnable interface.
If you are not extending the Thread class,your class object would not be treated as a thread object. So you have to explicitly create Thread class object.
Thread class will take Runnable class as parameter in constructor.
You are passing the object of your class X that implements Runnable to Thread constructor so that your class run() method will be executed from start() method of Thread.
You can create threads in two different ways. Have a look at oracle documentation about thread creation
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}

understanding java code for thread

I was just reviewing some java code and I came across the below program
public class LengthOfString extends Thread {
static String s;
public void run(){
System.out.println("You Have Enter String: " + s +" Length Of It is :" + s.length());
}
public static void main(String[] args) throws InterruptedException {
s = "This IS String";
LengthOfString h = new LengthOfString(); //creating the object of class
Thread t = new Thread(h); //why we have passed this object here???
t.start();
}
}
I understood that it is used to print string length, but I have a problem understanding the commented line. Please help me to understand why this implementation was used.
Actually in java, there are 2 ways to create a Thread .
Provide a Runnable object. The Runnable interface defines a single
method, run, meant to contain the code executed in the thread. The
Runnable object is passed to the Thread constructor.
Subclass Thread. The Thread class itself implements Runnable, though
its run method does nothing. An application can subclass Thread,
providing its own implementation of run.
You chosen the second one and you can simply write
new LengthOfString().start();
instead
LengthOfString h=new LengthOfString(); //creating the object of class
Thread t=new Thread(h); //why we have passed this object here???
t.start();
Edit:
Thread class have a constructor public Thread(Runnable target), that it takes Runnable type as a parameter and when you pass that to thread class it calls the implementation of run() method when you start that thread.
In this case, you don't need the Thread t=new Thread(h) line, because LengthOfString extends Thread. Many times though, you implement the Runnable Interface. In that case, you need to create a Thread object with a Runnable argument in the constructor, because Runnable Objects dont have a start methods

How does JVM know about which run method to be called while executing start() method

In the code given below I have passed the Temp class object's reference id inside the Thread constructor call which would be catched by thread class's constructor in Runnable type reference variable. so I want to ask that is there any code inside that Thread class constructor which tells the JVM that this particular class's run() method is to be executed when a thread is created.
class Temp implements Runnable
{
public void run()
{
System.out.println("Hello from a thread!");
}
public static void main(String args[])
{
(new Thread(new Temp())).start();
}
}
Inside the thread.start() method, the thread calls runnable.run().
A simple way of how this could work but really, it's not done this way due to this example not creating a new thread, is
public class Thread {
private Runnable runnable;
public Thread(Runnable runnable) {
this.runnable = runnable;
}
public void start() {
if (runnable != null) {
runnable.run();
}
}
}
Then when you call:
new Thread(this).start();
A new Thread will be created, assigning the Runnable this to the inner private member. Later, after the object is created, start() will be called on the object, which will look up the private runnable member, and call it's run() method.
start() is the command to begin using the thread that you specified in method run(). Whenever start() is called, it will execute code in the run() method.
You passed in a Temp object as the Thread's Runnable. Thread.start will call the run method of its Runnable, so Temp.run is going to get called.
Thread's start method calls the run method of the object you pass as an argument to the constructor. Since you pass an object of class Temp, Temp's run method will be called.
What happens (in general) is this.
The Thread.start() method allocates the stack, and so on.
Then it calls the Thread.run() method.
If you have overridden Thread.run(), then your override run() method is called.
This does ... basically what you told it to do.
Otherwise, the run() method implemented by Thread itself is called.
The Thread.run() method checks to see if the Thread instance has a Runnable instance.
If it does, then Thread.run() calls the run() method on the Runnable().
Otherwise, the Thread.run() method simply returns.
Then the Thread.run() method returns (or terminates abnormally), the start() method marks the Thread as no longer alive, and releases the stack and dismantles other stuff associated with the Thread object.
Is there any code inside that Thread class constructor which tells the JVM that this particular class's run() method is to be executed when a thread is created.
Not exactly. The constructor stores the Runnable in a private variable, and the Thread.run() method tests the private variable ... if Thread.run() hasn't been overridden.

What is the main advantage of extending Thread class (or when to extend Thread instead of implement runnable)

I'm trying to find out what are the possible advantages of extending the Thread class would be?
This is a part of another question which I describe:
There is two way of creating threads in Java
extending from Thread class
implementing the runnable interface
As expalined here there are several benefits of using runnable interface. My question is what is the advantage of extending from Thread class? The only advantage that comes to my mind is that one can extend from Thread class, and let's say call it ThreadExtended class. Then he/she can add more functionality in ThreadExtended(which I don't know what that might be), and then when he/she wants to create a thread, instead of extending from Thread class, it extends from ThreadExtended.
Is there any advantages in using Thread class instead of Runnable interface? Do you know any class(es) that extends from Thread class and then ask users to extends from those classes if they want to have multithreading capabilities?
public class ThreadExtended extends Thread{
//override some functions || add more functionality to Thread class
}
public class MyThread extends ThreadExtended{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Using ThreadExtended instead of Thread directly");
}
}
public static void main(String args[])
{
MyThread myThread = new MyThread();
myThread.start();
}
}
There is rarely a compelling reason to extend the Thread class. I would imagine that in most cases, you would end up just throwing all of your 'do some stuff' logic into the run method anyway.
You should definitely stick with implementing Runnable. By choosing to extend Thread, you are creating a class hierarchy that probably is nonsensical and will wind up restricting your options for refactoring things in the future. By choosing to implement Runnable, you make no demands of what the lineage of the implementer is, and you can use powerful abstractions like the ExecutorService to abstract away the nuts and bolts of running a chunk of code. Finally, preferring to implement an interface rather than extend a class is a good practice!
The only reason to extend Thread is if you need to add behavior that is associated with the thread itself, rather than the task that the thread is executing.
For example, if you're implementing a thread pool (which nobody should do anymore, given java.util.concurrent), you would need to change the behavior of the thread so that (1) it can accept new work, and (2) it returns itself to the pool. In a very simplified form:
public void setRunnable(Runnable runnable) {
this.runnable = runnable;
}
public void run() {
while (true) {
// wait on lock
try {
this.runnable.run();
}
catch (Throwable ex) {
// do something with exception
}
finally {
// return to pool
}
}
}
I find it clearer to extend Thread if I also configure the thread, for instance:
class FileReaper extends Thread {
FileReaper() {
setDaemon(true);
setName(getClass().getSimpleName());
}
#Override public void run() {
// do something
}
}
Simply put, when you extend Thread that will be the only class you will be extending from!
There is also a good reason to extend a Thread - if you want to create a Looper Thread:
This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
The UI thread is a Looper Thread, but you might want to create your own worker Looper Thread. To learn how the Thread with a Looper running its loop() method on it behaves, see my recent answer here.

What does a block of code do after a new operation in Java?

SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
Here a block of code follows new Runnable(). How do I understand this code? I don't remember we can pass a code block directly to any object in java.
It is not a code block. It is an object.
When you say,
new Runnable()
you are creating an object that implements the Runnable interface, specifically the run() method.
As the method name suggests, invokeLater() will invoke the run() method of your runnable interface implementation object (or Runnable object) at some later point in time.
As another poster mentioned, this is an example of Anonymous Classes. It is really a convenience mechanism to quickly write code in a more concise fashion. If you don't like this, you can do it this way -
Create a new class that implements Runnable -
public class RunnableImplementation implements Runnable
{
public void run()
{
Example ex = new Example();
ex.setVisible(true);
}
}
Then, the code in your example becomes -
SwingUtilities.invokeLater(new RunnableImplementation());
It's creating an instance of an anonymous inner class. Rather than deriving a named class from Runnable and creating an instance of it, you can do the whole thing inline.
See Anonymous Classes.
You are not passing any code block, you are actually overriding the run method of the Runnable class
How do understand this code? This is such called swing event queue which helps to prevent concurrency problems. It invokes method run() on each Runnable object in this queue in sequential order.
Your code
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
is equivalent to
SwingUtilities.invokeLater(new MyRunnable() );
where MyRunnable is a class that implements the Runnable interface with the code you have and is created only for this purpose and cannot be used again.
Note MyRunnable is not the actual name, just made it up to show the point.

Categories