3.4 KiB
Q1
public class StartVsRun {
static class MyRunnable implements Runnable {
public void run() {
System.out.println("Running in: " + Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
System.out.println("Calling run()");
t1.run();
Thread.sleep(100);
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
System.out.println("Calling start()");
t2.start();
}
}
Answer
Output
the program first outputs Calling run()
then it runs the t1 by calling the run method in the t1 thread
t1's run method outputs Running in: Thread-1
the program waits 100ms (Thread.sleep(100)) after that a new thread is created called t2
the program outputs Calling start() and then Running in: Thread-2
Difference between run() and start()
when we call t1.run() the program stops at this line, no new thread would be created and run method runs on the main thread
but when we call t2.start() a new thread would get created and main thread runs alongside the new thread.
Q2
public class DaemonExample {
static class DaemonRunnable implements Runnable {
public void run() {
for(int i = 0; i < 20; i++) {
System.out.println("Daemon thread running...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//[Handling Exception...]
}
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(new DaemonRunnable());
thread.setDaemon(true);
thread.start();
System.out.println("Main thread ends.");
}
}
Answer
Output
The program creates a thread from DaemonRunnable class, after that it sets to a be a daemon output first message: Daemon thread running... and just as it's in sleep (Thread.sleep(500)) the main thread finishes its job
and outputs: Main thread ends.. this would end the daemon thread we started.
What if we removed thread.setDaemon(true)
if we removed this line thread would've been a normal thread, meaning when we reach the end of the main thread thread would still continue doing its work (which is printing Daemon thread running...)
The Main thread would've waited for thread to finish its job before ending the program.
Real life use cases
sshd is a daemon that listens for any SSH connections to the computer
another example would be systemd which is a daemon on most of the linux distros that manages services
Q3
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running using a ...!");
});
thread.start();
}
}
Answer
Output
the program simply just outputs Thread is running using a ...!
What is the () -> {...} syntax called
() -> {...} is a lambda expression with no parameters: ()
Difference between this and a normal class
using this lambda expression we don't need to create another class