Skip to content

Commit eb13603

Browse files
committed
lecture
1 parent 9cd1a89 commit eb13603

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
}

0 commit comments

Comments
 (0)