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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With