File tree 4 files changed +43
-3
lines changed
src/main/java/io/concurrency/chapter04/exam03
4 files changed +43
-3
lines changed Original file line number Diff line number Diff line change 1
1
package io .concurrency .chapter04 .exam03 ;
2
2
3
3
public class DaemonThreadLifeCycleExample {
4
+
4
5
public static void main (String [] args ) throws InterruptedException {
5
6
Thread userThread = new Thread (() -> {
6
7
try {
@@ -22,7 +23,7 @@ public static void main(String[] args) throws InterruptedException {
22
23
}
23
24
});
24
25
25
- daemonThread .setDaemon (true );
26
+ daemonThread .setDaemon (true ); //반드시 스레드 실행 전에 데몬으로 지정해야 함
26
27
daemonThread .setDaemon (false );
27
28
28
29
userThread .start ();
Original file line number Diff line number Diff line change
1
+ ## 사용자 스레드
2
+
3
+ 모든 사용자 스레드가 종료되어야 애플리케이션 종료!!
4
+ 이 때 메인 스레드가 먼저 종료되든 나중에 종료되든 상관 X
5
+ (메인 스레드도 사용자 스레드니까... 일반적인 사용자 스레드와 다른 점은 JVM이 자동으로 생성한다는 것)
6
+
7
+ ## 부모 스레드 자식 스레드
8
+ 사용자 스레드는 사용자 스레드를 낳고
9
+ 데몬 스레드는 데몬 스레드를 낳는다
10
+
11
+ ## 스레드 데몬 설정
12
+ - thread.setDaemon(true) 사용
13
+ - 반드시 스레드 실행 전에 설정해야 하며, 실행 중에 데몬으로 설정하면 IllegalThreadStateException 발생!!
Original file line number Diff line number Diff line change 1
1
package io .concurrency .chapter04 .exam03 ;
2
2
3
3
public class UserAndDaemonInheritanceExample {
4
+
5
+ public void test (){
6
+
7
+
8
+ new Thread (() ->{
9
+ new Thread (() -> {
10
+ System .out .println ("사용자 스레드의 자식 스레드 데몬 상태: " + Thread .currentThread ().isDaemon ());
11
+ }).start ();
12
+ System .out .println ("사용자 스레드의 데몬 상태: " +Thread .currentThread ().isDaemon ());
13
+
14
+ }).start ();
15
+
16
+
17
+ Thread daemonThread = new Thread (() -> {
18
+ new Thread (() -> {
19
+ System .out .println ("데몬 스레드의 자식 스레드 데몬 상태: " + Thread .currentThread ().isDaemon ());
20
+ }).start ();
21
+ System .out .println ("데몬 스레드의 데몬 상태: " + Thread .currentThread ().isDaemon ());
22
+
23
+ });
24
+
25
+ daemonThread .setDaemon (true );
26
+ daemonThread .start ();
27
+
28
+ }
4
29
public static void main (String [] args ) {
5
30
6
31
// 사용자 스레드 생성
Original file line number Diff line number Diff line change 1
1
package io .concurrency .chapter04 .exam03 ;
2
2
3
3
public class UserThreadLifecycleExample {
4
+
4
5
public static void main (String [] args ) throws InterruptedException {
5
6
// 사용자 스레드 1 생성
6
7
Thread userThread1 = new Thread (() -> {
@@ -32,8 +33,8 @@ public static void main(String[] args) throws InterruptedException {
32
33
userThread2 .start ();
33
34
34
35
// 메인 스레드가 userThread1과 userThread2의 종료를 기다립니다.
35
- // userThread1.join();
36
- // userThread2.join();
36
+ userThread1 .join ();
37
+ userThread2 .join ();
37
38
38
39
System .out .println ("모든 사용자 스레드가 종료되었습니다. 메인 스레드 종료." );
39
40
}
You can’t perform that action at this time.
0 commit comments