-1

The Thread class does not contain constructor which takes Object type as parameter so how it calls the constructor during multi-threading. Below is the code in which i need explanation.

Thread t = new Thread(myThread); //How this line execute.

class MyThread implements Runnable  
{  
    @Override  
    public void run()
    {    
        for(int i = 0; i < 1000; i++)
        {
            System.out.println(i+" * "+(i+1)+" = " + i * (i+1));
        }
    }
}

public class ThreadsInJava
{
    //Main Thread
    public static void main(String[] args)
    {
        MyThread myThread = new MyThread();  

        Thread t = new Thread(myThread);     

        t.start();                          
    }
}
CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • 1
    Can you explain what is the problem here? You are creating a thread object which has Runnable as constructor param so it initializes a new thread and that thread calls your run method. Are you confused that your MyThread class is of type Runnable so the Thread knows it has run method? – maslan Jun 13 '19 at 08:25

3 Answers3

4

The Thread constructor takes an Runnable as parameter. Your class implements the Runnable so it can be given to the constructor because the class is an Runnable after implementing it.

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
3

Your class MyThread implements the Runnable interface.

That Thread constructor accepts anything that implements Runnable. If you would remove that clause implements Runnable (together with the @Override annotation), it would no longer work!

That is all there is to this!

For further insights, I suggest to read What does it mean to program against an interface.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

I don't know exactly where your confusion lies, but there exists a Thread constructor which takes a Runnable. Your MyThread class implements Runnable, so it can be passed as a Runnable argument.

By the way, you don't have to write a whole class implementing Runnable. Because Runnable is a functional interface, you could use a lambda expression:

new Thread(() -> {
    for (int i = 0; i < 1000; i++) {
        System.out.println(i + " * " + (i + 1) + " = " + i * (i + 1));
    }
}).start();
MC Emperor
  • 22,334
  • 15
  • 80
  • 130