HW08
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
Report
|
||||
|
||||
1. start() vs run()
|
||||
|
||||
What output do you get from the program? Why?
|
||||
|
||||
The output is usually something like this:
|
||||
Calling run()
|
||||
Running in: main
|
||||
Calling start()
|
||||
Running in: Thread-2
|
||||
|
||||
When we call "run()" directly, no new thread is created and the code runs in the main thread. That's why "main" is printed.
|
||||
|
||||
However, when we call "start()", Java creates a new thread and then executes the "run()" method inside that thread, so the thread name becomes "Thread-2".
|
||||
|
||||
What's the difference between calling "start()" and "run()"?
|
||||
|
||||
The "run()" method behaves like a normal method call and does not create a new thread.
|
||||
|
||||
The "start()" method creates a new thread and allows concurrent execution. Internally, it automatically calls the "run()" method.
|
||||
|
||||
---
|
||||
|
||||
2. Daemon Threads
|
||||
|
||||
What output do you get from the program? Why?
|
||||
|
||||
The output is usually:
|
||||
|
||||
Main thread ends.
|
||||
|
||||
Sometimes a few lines of
|
||||
|
||||
Daemon thread running...
|
||||
|
||||
may also appear.
|
||||
|
||||
This happens because daemon threads run in the background. As soon as the main thread finishes, the JVM stops all daemon threads, even if they have not completed their work.
|
||||
|
||||
What happens if you remove "thread.setDaemon(true)"?
|
||||
|
||||
If we remove this line, the thread becomes a normal user thread. In this case, the JVM waits until the thread finishes all 20 iterations before terminating the program.
|
||||
|
||||
What are some real-life use cases of daemon threads?
|
||||
|
||||
Examples include:
|
||||
|
||||
- Garbage collection
|
||||
- Background logging
|
||||
- Cache cleanup
|
||||
- Monitoring system resources
|
||||
- Periodic maintenance tasks
|
||||
|
||||
---
|
||||
|
||||
3. A shorter way to create threads
|
||||
|
||||
What output do you get from the program?
|
||||
|
||||
Thread is running using a ...!
|
||||
|
||||
What is the "() -> { ... }" syntax called?
|
||||
|
||||
This syntax is called a Lambda Expression.
|
||||
|
||||
How is this code different from creating a class that extends "Thread" or implements "Runnable"?
|
||||
|
||||
Using lambda expressions makes the code shorter and easier to read. Instead of creating a separate class for "Runnable", we can write the thread's behavior directly where we create the thread.
|
||||
|
||||
This reduces extra code and makes the program cleaner.
|
||||
Reference in New Issue
Block a user