-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDaemonThread.java
More file actions
56 lines (45 loc) · 1.76 KB
/
DaemonThread.java
File metadata and controls
56 lines (45 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class MyDaemon extends Thread{
//assign thread a name!
public MyDaemon(String name) {
super(name); // Set thread name
}
public void run(){
while(true){
System.out.println("Daemon Thread is running!");
try {
Thread.sleep(1000); //1sec
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class DaemonThread {
public static void main(String args[]){
MyDaemon th = new MyDaemon("Wolverine"); //pass name of thread!
th.setName("Wolverine"); // or directly like this! Set thread name!
//we tell that thread is daemon,
//daemon will stop once the main thread completes execution!
//so no infinite loop
//if this line is removed,then it is user thread,
//JVM will run this thread infinitely since while(true) is there!
//even main completes exec, user thread will run indefinitely.args
//but incase of daemon, after 3 seconds , main will complete its execution and
//also stopping the execution of daemon thread! wow!
//✅ JVM will exit if only daemon threads are running.
//🚫 JVM will NOT exit if any user thread is still running.
//If all user threads finish, JVM stops automatically.
th.setDaemon(true);
th.start();
System.out.println("Main thread is running!");
try {
Thread.sleep(3000); //1sec
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finishing, Daemon thread will exit.");
System.out.println("Main thread finishing, Daemon thread will exit.");
}
}