Files
2026-06-04 19:52:17 +04:30

1.6 KiB

Answers to Theoretical Questions

1. start() vs run()

Output:

Calling run()
Running in: main
Calling start()
Running in: Thread-2
  • When calling run method, no matter what thread it is called through, the program uses the thread it is called in. So here, the run method would be runed in the main thread.

  • On the other hand, the start method runs the run method in the thread in which it is created or overridden. In this case, it would be the second thread.

  • Hence, the key difference between the two methods run & start is where they run the runnable method given to the thread.


2. Daemon Threads

Output:

Main thread ends.
Daemon thread running...
  • By turning the thread into a daemon thread, the program only runs until the last user thread finishes its task; shortly after that, the program running ends ignoring the daemon threads and their left tasks.

  • If we remove thread.setDaemon(true) from the code, the thread would be considered a user thread. The program runs until the thread finishes its task. Here, it would print Daemon thread running... 20 times in total.

  • Two real-life use cases of daemon threads are garbage collectors and auto-save features in editors.


3. A shorter way to create threads

Output:

Thread is running using a ...!
  • the () -> { ... } syntax is called a lambda expression.

  • By using a lambda expression, there is no need for creating a whole class to run the task. It also decreases the number of lines we need to code. So it is recommended over using another class especially if the method we want to run is not complicated.