ThreadWorker does not execute when I use method reference for creating new object in the constructor of Thread or passing Lambda for creation of new Object.
But it works fine when I create ThreadWorker object separately and I pass that to Thread class.
public class RunnableImpl {
public static void main(String[] args) throws InterruptedException {
ThreadWorker th= new ThreadWorker();
Thread t1 = new Thread(th);
t1.start();
t1.join();
System.out.println("Main method terminated");
}
}
class ThreadWorker implements Runnable {
@Override
public void run() {
int[] arr = { 1, 4, 8, 9, 1, 0, 4, 5, 4 };
System.out.println(Arrays.stream(arr).sum());
}
}
If I use lambda for example:
Thread t1 = new Thread(ThreadWorker :: new);
or
Thread t1 = new Thread(() ->new ThreadWorker());
then there is no output but If I create ThreadWorker Object separately then the program is working fine.
Can someone please let me know, how it is possible?
new ThreadWorker()insted of() ->new ThreadWorker()orThreadWorker :: new.