1.8 KiB
Advanced Programing - 8 Report
Theoretical Questions Answers
1. start() vs run()
Output:
-Calling run() -Running in: main -Calling start() -Running in: Thread-2
Explanation
When calling "t1.run()" directly, the run method executes in the current thread (main). When calling "t2.start()" , java creates a new thread and executes run() in that thread (Thread-2).
Difference:
| start() | run() |
|---|---|
| Creates new thread | No new thread |
| Executes run() in new thread | Executed like nurmal method |
| Can only be called once | Can be called multiple times |
Deamon Threads
Output(with demon):
-Main thread ends -Deamon thread running... -(Program terminates quickly)
Output(without demon):
-Main thread ends. -Deamon thread running... -(20 times)
Explanation
-A daemon thread is a background thread that does NOT prevent the JVM from exiting. When the main thread (non-daemon) finishes, the JVM checks if there are any non-daemon threads still running. Since only the daemon thread remains, the JVM terminates immediately without waiting for the daemon thread to complete its 20 iterations.
-Without setDaemon(true), the thread becomes a user thread (non-daemon) . User threads prevent the JVM from exiting until they complete. Therefore, the JVM waits for the thread to finish all 20 iterations before terminating the program.
Real-life use cases:
- Garbage Collector (GC)
- Auto-save features
- Background logging
- Session cleanup in web servers
3. Lambda Expressions
Output:
-Thread is running using a...!
What is () -> {}?
This is a Lambda Expression introduced in Java.
Comparison:
| Traditional | Lambda |
|---|---|
| Needs separate class | No separate class |
| More code | Concise |
new Thread(new Runnable(){...}) |
new Thread(() -> {...}) |