Files
2026-06-07 00:25:19 +03:30

124 lines
4.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 1 . `start()` vs `run()` :
```
public class StartVsRun {
static class MyRunnable implements Runnable {
public void run() {
System.out.println("Running in: " + Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
System.out.println("Calling run()");
t1.run();
Thread.sleep(100);
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
System.out.println("Calling start()");
t2.start();
}
}
```
### Questions and Answers:
* **What output do you get from the program? Why?**
* ```
//output:
Calling run()
Running in : main
Calling start()
Running in : Thread-2
```
* *When `t1.run()` is called directly, it executes the `run()` method in the current thread (the main thread), just like a normal method call. No new thread is created. Therefore, `Thread.currentThread().getName()` returns `"main"`.*
<br>
* *When `t2.start()` is called, it creates a new thread named `"Thread-2"` and the JVM automatically invokes the `run()` method inside that new thread. Hence, `Thread.currentThread().getName()` returns `"Thread-2"`.*
<br>
* **Whats the difference in behavior between calling `start()` and `run()`?**
<br>
* *Calling `run()` directly just executes the code inside `run()` in the caller's thread it's not multithreading.*
<br>
* *Calling `start()` schedules the thread to run, and the `run()` method will be executed in a separate thread concurrently.*
***
## 2. Daemon Threads :
```
public class DaemonExample {
static class DaemonRunnable implements Runnable {
public void run() {
for(int i = 0; i < 20; i++) {
System.out.println("Daemon thread running...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//[Handling Exception...]
}
}
}
}
public static void main(String[] args) {
Thread thread = new Thread(new DaemonRunnable());
thread.setDaemon(true);
thread.start();
System.out.println("Main thread ends.");
}
}
```
### Questions and Answers:
* **What output do you get from the program? Why?**
* ```
//output:
Main thread ends.
Daemon thread running...
Daemon thread running...
...
//(less than 20 times)
```
* *The main thread prints `"Main thread ends."` and then terminates.*
<br>
* *The other thread is a `daemon thread`. Daemon threads are background threads that do not prevent the JVM from exiting.*
<br>
* *When the last non-daemon thread (in this case, only the main thread) finishes, the JVM terminates immediately without waiting for the daemon thread to complete its loop.*
<br>
* *Therefore, the daemon thread only gets to print a few lines before the program shuts down. It never reaches 20 iterations.*
<br>
* **What happens if you remove thread.setDaemon(true)?**
<br>
* *The thread prints 20 times and then the program ends, because the thread is no longer a daemon (it becomes a regular user thread).*
* **What are some real-life use cases of daemon threads?**
<br>
1. *Background music in a game While you play, music plays in the background. When you close the game, the music stops immediately. No need to finish the song.*
<br>
2. *Auto-save in a text editor Every few minutes, the program saves your file automatically. If you close the program, it doesn't matter if the auto-save finishes or not. Just stop.*
<br>
***
## 3. A shorter way to create threads :
```
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running using a ...!");
});
thread.start();
}
}
```
### Questions and Answers:
* **What output do you get from the program?**
* ```
//output:
Thread is running using a ...!
```
* **What is the `() -> { ... }` syntax called?**
<br>
* *It is called a Lambda Expression*
<br>
* **How is this code different from creating a class that extends `Thread` or implements `Runnable`?**
<br>
* *Shorter and cleaner code.*
* *No need for a separate class or explicit `run()` override.*
* *Lambda directly provides the `run()` body.*