-2

Struture 1 :

public class Runner {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread(){
            public void run() {
                System.out.println("value :");
            }
        });
        t1.start();
    }
}

Structure 2 :

public class Runner {
    public static void main(String[] args) {
        Thread t1 = new Thread(){ 
            public void run(){
                System.out.println("value :"); 
            }
        };
        t1.start();
    }
}

Result in both the cases is same.

What is the difference between the two above mentioned structres? Please explain.

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
v0001
  • 11
  • 1
  • 3

2 Answers2

0

You are executing thread using inner class in your first example. So basically you are passing object of one thread to another thread in your first example.

start() method always looks for run method. And t1.start() running there thread in both the example.

KP_JavaDev
  • 222
  • 2
  • 4
  • 11
0

In the first example you provide the Thread with a Thread in the constructor. Its weird, and it works because Thread implements Runnable, but the usage of it like this is discouraged. Just use Runnable in the constructor

By default, Thread's run() method just runs the Runnable given to the constructor. If you don't provide a Runnable, and neither override the run method of the Thread, then it will basically execute no code.

The decompiled run method of my Thread class looks like this:

public void run() {
    if(this.target != null) {
        this.target.run();
    }
}
kupsef
  • 3,357
  • 1
  • 21
  • 31