+ 1

Why is there an object as an argument in this multi-thread example?

What is the purpose of the line with the 2 new’s in it? class Loader implements Runnable { public void run() { System.out.println("Hello"); } } class MyClass { public static void main(String[ ] args) { Thread t = new Thread(new Loader()); t.start(); } }

26th May 2019, 11:17 PM
Roger Wang
Roger Wang - avatar
1 ответ
+ 1
The Thread object "t" is initialized to a new Thread object. the Thread constructor requires a Runnable instance (that's being created with the new keyword) as an argument. After that, the t.start() method fires the Loader's "run()" method. Remember that a Loader is a child of Runnable that overrides the run method. That's why the new Loader can be used as a Runnable object.
26th May 2019, 11:30 PM
Andres0b0100
Andres0b0100 - avatar