Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 963
karan Avatar asked Mar 16 '26 22:03

karan


1 Answers

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.

like image 110
Suresh Atta Avatar answered Mar 19 '26 12:03

Suresh Atta