File tree Expand file tree Collapse file tree 1 file changed +83
-0
lines changed
src/main/java/io/concurrency/chapter02/exam03 Expand file tree Collapse file tree 1 file changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ package io .concurrency .chapter02 .exam03 ;
2
+
3
+ public class ThreadLifecycleExample {
4
+
5
+ public static void main (String [] args ) throws InterruptedException {
6
+
7
+ /**
8
+ * NEW 상태의 스레드 생성
9
+ */
10
+ Thread newThread = new Thread (() -> {});
11
+ System .out .println ("스레드 생성: " + newThread .getState ());
12
+
13
+ /**
14
+ * RUNNABLE 상태의 스레드 생성
15
+ */
16
+ Thread runnableThread = new Thread (() -> {
17
+ while (true ) {
18
+ // 무한 루프
19
+ }
20
+ });
21
+ runnableThread .start ();
22
+
23
+ /**
24
+ * TIMED_WAITING 상태의 스레드 생성
25
+ */
26
+ Thread timedWaitingThread = new Thread (() -> {
27
+ try {
28
+ Thread .sleep (10000 );
29
+ } catch (InterruptedException e ) {
30
+ e .printStackTrace ();
31
+ }
32
+ });
33
+ timedWaitingThread .start ();
34
+
35
+ /**
36
+ * WAITING 상태의 스레드 생성
37
+ */
38
+ final Object lock = new Object ();
39
+ Thread waitingThread = new Thread (() -> {
40
+ synchronized (lock ) {
41
+ try {
42
+ lock .wait ();
43
+ } catch (InterruptedException e ) {
44
+ e .printStackTrace ();
45
+ }
46
+ }
47
+ });
48
+ waitingThread .start ();
49
+ Thread .sleep (100 ); // 스레드 상태 변화를 위한 대기 시간
50
+
51
+ /**
52
+ * BLOCKED 상태의 스레드 생성
53
+ */
54
+ Thread runningThread = new Thread (() -> {
55
+ synchronized (lock ) {
56
+ while (true ) {
57
+ // 무한 루프로 lock 을 계속 점유
58
+ }
59
+ }
60
+ });
61
+ runningThread .start ();
62
+ Thread .sleep (100 ); // runningThread 가 lock을 점유하도록 잠시 대기
63
+
64
+ Thread blockedThread = new Thread (() -> {
65
+ synchronized (lock ) {
66
+ }
67
+ });
68
+ blockedThread .start ();
69
+ Thread .sleep (100 ); // blockedThread 가 lock을 기다리는 상태로 대기
70
+
71
+ /**
72
+ * TERMINATED 상태
73
+ */
74
+ newThread .start ();
75
+ newThread .join ();
76
+
77
+ System .out .println ("스레드 실행: " + runnableThread .getState ());
78
+ System .out .println ("스레드 지정된 시간 대기: " + timedWaitingThread .getState ());
79
+ System .out .println ("스레드 대기: " + waitingThread .getState ());
80
+ System .out .println ("스레드 차단: " + blockedThread .getState ());
81
+ System .out .println ("스레드 종료: " + newThread .getState ());
82
+ }
83
+ }
You can’t perform that action at this time.
0 commit comments