51 lines
1.6 KiB
Markdown
51 lines
1.6 KiB
Markdown
## Question 1
|
|
output:
|
|
```angular2html
|
|
Calling run()
|
|
Running in: main
|
|
Calling start()
|
|
Running in: Thread-2
|
|
```
|
|
note that there will be a 100ms pause before calling start.
|
|
|
|
when calling `t1.run()` no other thread will be created and `Thread.currentThread().getName()` returns the thread that was already running.
|
|
|
|
but when calling `t2.start()` a branch new thread gets created alongside the main one named _Thread-2_.
|
|
|
|
## Question 2
|
|
output:
|
|
```angular2html
|
|
Main thread ends.
|
|
Daemon thread running...
|
|
```
|
|
when we use `setDaemon(true)` method for a thread it means that there is no need for _JVM_ to wait for this thread to finish its job and end the program.
|
|
|
|
So if we call `thread.start()` after setting the thread a daemon one a new daemon thread gets created and as soon as there is time for the main thread (because of the 0.5 second pause) it finishes the program.
|
|
|
|
If we were not to set the thread a daemon, we could see the expression `Daemon thread running...` 20 times which 0.5 second pauses.
|
|
|
|
It is useful for health check and monitoring, cache eviction etc...
|
|
|
|
## Question 3
|
|
output:
|
|
```angular2html
|
|
Thread is running using a ...!
|
|
```
|
|
`() -> { ... }` is called a _Lambda Expression_.
|
|
If we were to write this functionality in a simple way and not in lambda:
|
|
```java
|
|
public class ThreadDemo {
|
|
|
|
static class MyRunnable implements Runnable {
|
|
@Override
|
|
public void run() {
|
|
System.out.println("Thread is running using a ...!");
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
Thread thread = new Thread(new MyRunnable());
|
|
thread.start();
|
|
}
|
|
}
|
|
``` |