diff --git a/.idea/markdown.xml b/.idea/markdown.xml new file mode 100644 index 0000000..c61ea33 --- /dev/null +++ b/.idea/markdown.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/REPORT.md b/REPORT.md new file mode 100644 index 0000000..2b13ff9 --- /dev/null +++ b/REPORT.md @@ -0,0 +1,64 @@ +# Report + +## 1. start() vs run() + +Output: + +```text +Calling run() +Running in: main +Calling start() +Running in: Thread-2 +``` + +When `run()` is called directly, it runs like a normal method, so it is executed by the main thread. + +When `start()` is called, Java creates a new thread, and then the `run()` method runs inside that new thread. That is why the second output shows `Thread-2`. + +So, `run()` does not start a new thread, but `start()` does. + +--- + + +## 2. Daemon Threads + +The output is not always the same. The main thread prints: + +```text +Main thread ends. +``` + +and then finishes. Since the created thread is marked as a daemon thread using `setDaemon(true)`, the JVM does not wait for it to complete. As a result, the program may stop before the daemon thread finishes all 20 iterations. Depending on the scheduling, the message + +```text +Daemon thread running... +``` + +may appear a few times or may not appear at all. + +If `setDaemon(true)` is removed, the thread becomes a normal user thread. In that case, the JVM waits for the thread to finish, and the message + +```text +Daemon thread running... +``` + +will be printed 20 times before the program exits. + +Daemon threads are commonly used for background tasks such as logging, monitoring, and cleanup operations. + + + + +## 3. A shorter way to create threads + +Output: + +```text +Thread is running using a ...! +``` + +The syntax `() -> { ... }` is called a lambda expression. + +It is a shorter way to write a `Runnable`. Instead of creating a separate class or anonymous class, we write the thread task directly inside the `Thread` constructor. + +This makes the code shorter and easier to read.