Files
2026-06-08 17:03:30 +03:30

1.9 KiB
Raw Permalink Blame History

Question 1:

Output

Calling run()
Running in: main
Calling start()
Running in: Thread-2

When we call t1.run(), we are just calling a method in the current thread(the main thread). No extra thread is created.

But if we call t2.start(), the code runs in a separate thread and use multithreading.

Question 2:

Output:

Main thread ends.
Daemon thread running...
  • The main thread finishes immediately and the other thread is stopped right after because it's a daemon thread.

  • If we remove thread.setDaemon(true), the thread won't be a daemon anymore. So when the main thread finishes, the other thread will continue and the output would be :

Main thread ends.
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
  • Background Tasks: Tasks that shouldnt block the application from shutting down. Examples: Garbage Collection: Memory management. Auto-save: Periodically saving temporary drafts. Monitoring/Heartbeats: Checking system health or connection status in the background.

Question 3:

Output:

Thread is running using a ...!
  • Syntax: This is a Lambda Expression, a shortcut in to write code blocks (functions) concisely.
  • Difference: Your code is just a shorter version of the standard implements Runnable approach. You dont need to create a separate class anymore; you just pass the logic directly as a lambda. Its cleaner and less boilerplate code.