1.6 KiB
Question 1
output:
Calling run()
Running in: main
Calling start()
Running in: Thread-2
note that there will be a 100ms pause before calling start.
when calling t1.run() no other thread will be created and Thread.currentThread().getName() returns the thread that was already running.
but when calling t2.start() a branch new thread gets created alongside the main one named Thread-2.
Question 2
output:
Main thread ends.
Daemon thread running...
when we use setDaemon(true) method for a thread it means that there is no need for JVM to wait for this thread to finish its job and end the program.
So if we call thread.start() after setting the thread a daemon one a new daemon thread gets created and as soon as there is time for the main thread (because of the 0.5 second pause) it finishes the program.
If we were not to set the thread a daemon, we could see the expression Daemon thread running... 20 times which 0.5 second pauses.
It is useful for health check and monitoring, cache eviction etc...
Question 3
output:
Thread is running using a ...!
() -> { ... } is called a Lambda Expression.
If we were to write this functionality in a simple way and not in lambda:
public class ThreadDemo {
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running using a ...!");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}