Skip to content

Commit 83dc6cb

Browse files
committed
sleep()
1 parent d3e155c commit 83dc6cb

15 files changed

+147
-35
lines changed

src/main/java/io/concurrency/chapter02/exam02/MultiThreadAppTerminatedExample.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ public class MultiThreadAppTerminatedExample {
44
public static void main(String[] args) {
55

66
for (int i = 0; i < 3; i++) {
7-
Thread thread = new Thread(new ThreadStackExample.MyRunnable(i));
7+
Thread thread = new Thread(new MyRunnable(i));
88
thread.start();
99
}
1010

src/main/java/io/concurrency/chapter02/exam02/README.md

+32-1
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,35 @@ main: 메인 스레드 종료
5050
Thread-2 : 스레드 실행중..
5151
```
5252
- 스레드는 독립적으로 동작하기 때문에 메인 스레드가 종료된 후에도 새로운 스레드가 생성됨을 확인 가능
53-
- thread3.run()을 했기 때문에 main 스레드에서 run()이 동작했음을 확인 가능 (즉 새로운 스레드 생성 x)
53+
- thread3.run()을 했기 때문에 main 스레드에서 run()이 동작했음을 확인 가능 (즉 새로운 스레드 생성 x)
54+
55+
# ThreadStackExample
56+
57+
문자열 리터럴은 불변 객체로서, JVM에 힙 영역 내의 String Pool에 저장<br>
58+
따라서 스레드가 문자열 리터럴 객체를 생성하는 함수를 실행하면, 문자열 객체는 스레드 스택이 아니라 힙에 생성된다<br>
59+
스레드 스택은 문자열 객체의 참조를 갖게 된다
60+
ex)
61+
```java
62+
private void secondMethod(int localValue) {
63+
String objectReference = threadId +" : Hello World";
64+
System.out.println(Thread.currentThread().getName() + " : 스레드 ID : "+threadId + " Value : "+localValue);
65+
}
66+
```
67+
68+
# MultiThreadAppTerminatedExample
69+
70+
```java
71+
메인 스레드 종료
72+
Thread-1: 스레드 실행 중...
73+
Thread-2: 스레드 실행 중...
74+
Thread-0: 스레드 실행 중...
75+
Thread-1 : 스레드 ID : 1, Value:101
76+
Thread-0 : 스레드 ID : 0, Value:100
77+
Thread-2 : 스레드 ID : 2, Value:102
78+
```
79+
메인 스레드가 먼저 종료되어도 애플리케이션 자체는 종료되지 않는다<br>
80+
메인 스레드가 생성한 사용자 스레드가 완전히 종료돼야 어플리케이션이 종료된다<br>
81+
82+
# SingleThreadAppTerminatedExample
83+
84+
메인 스레드가 종료되면 어플리케이션 종료
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,35 @@
11
package io.concurrency.chapter02.exam02;
22

33
public class ThreadStackExample {
4+
45
public static void main(String[] args) {
56

67
for (int i = 0; i < 3; i++) {
78
Thread thread = new Thread(new MyRunnable(i));
89
thread.start();
910
}
10-
1111
}
1212
static class MyRunnable implements Runnable{
1313

1414
private final int threadId;
15-
16-
public MyRunnable(int threadId) {
17-
15+
public MyRunnable(int threadId){
1816
this.threadId = threadId;
1917
}
20-
2118
@Override
2219
public void run() {
23-
System.out.println(Thread.currentThread().getName() + ": 스레드 실행 중...");
20+
System.out.println(Thread.currentThread().getName() + " : 스레드 실행 중.");
2421
firstMethod(threadId);
2522
}
2623

2724
private void firstMethod(int threadId) {
28-
2925
int localValue = threadId + 100;
3026
secondMethod(localValue);
31-
3227
}
3328

3429
private void secondMethod(int localValue) {
35-
String objectReference = threadId + ": Hello World";
36-
System.out.println(Thread.currentThread().getName() + " : 스레드 ID : " + threadId + ", Value:" + localValue);
30+
String objectReference = threadId +" : Hello World";
31+
System.out.println(Thread.currentThread().getName() + " : 스레드 ID : "+threadId + " Value : "+localValue);
3732
}
3833
}
34+
3935
}

src/main/java/io/concurrency/chapter02/exam03/BlockedStateThreadExample.java

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ public static void main(String[] args) throws InterruptedException {
2121
thread2.start();
2222
Thread.sleep(100); // thread2가 lock을 기다리는 상태로 대기
2323
System.out.println("스레드 2 상태: " + thread2.getState()); // BLOCKED
24+
2425
}
2526

2627
}

src/main/java/io/concurrency/chapter02/exam03/NewStateThreadExample.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
public class NewStateThreadExample {
44

55
public static void main(String[] args) {
6-
Thread thread = new Thread(() -> {
7-
System.out.println("스레드 실행 중");
8-
});
9-
System.out.println("스레드 상태: " + thread.getState()); // NEW
6+
7+
Thread thread = new Thread(() -> System.out.println("스레드 실행 중"));
8+
9+
System.out.println("스레드 상태 : "+thread.getState()); //NEW . 일반 객체를 생성한 상태와 같음
1010
}
1111

1212
}

src/main/java/io/concurrency/chapter02/exam03/RunnableStateThreadExample.java

+1
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@ public static void main(String[] args) throws InterruptedException {
1414
}
1515
});
1616
thread.start();
17+
1718
}
1819
}

src/main/java/io/concurrency/chapter02/exam03/TerminatedStateThreadExample.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public static void main(String[] args) throws InterruptedException {
77
System.out.println("스레드 실행 중");
88
});
99
thread.start();
10-
thread.join(); // 스레드가 종료될 때까지 기다림
10+
thread.join(); // 메인 스레드가 종료될 때까지 기다림
1111
System.out.println("스레드 상태: " + thread.getState()); // TERMINATED
1212
}
1313

src/main/java/io/concurrency/chapter02/exam03/ThreadLifecycleExample.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public static void main(String[] args) throws InterruptedException {
7272
* TERMINATED 상태
7373
*/
7474
newThread.start();
75-
newThread.join();
75+
newThread.join(); //메인 스레드 끝나면 종료
7676

7777
System.out.println("스레드 실행: " + runnableThread.getState());
7878
System.out.println("스레드 지정된 시간 대기: " + timedWaitingThread.getState());

src/main/java/io/concurrency/chapter02/exam03/TimedWaitingStateThreadExample.java

+7-4
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,20 @@
22

33
public class TimedWaitingStateThreadExample {
44

5-
public static void main(String[] args) throws InterruptedException {
5+
public static void main(String[] args) throws InterruptedException{
6+
67
Thread thread = new Thread(() -> {
78
try {
8-
Thread.sleep(10000);
9+
Thread.sleep(1000);
910
} catch (InterruptedException e) {
10-
e.printStackTrace();
11+
throw new RuntimeException(e);
1112
}
1213
});
14+
1315
thread.start();
1416
Thread.sleep(100);
15-
System.out.println("스레드 상태: " + thread.getState()); // TIMED_WAITING
17+
System.out.println("스레드 상태 : "+thread.getState());
18+
1619
}
1720

1821
}

src/main/java/io/concurrency/chapter02/exam03/WaitingStateThreadExample.java

+25-3
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,40 @@
33
public class WaitingStateThreadExample {
44

55
public static void main(String[] args) throws InterruptedException {
6-
final Object lock = new Object();
6+
7+
8+
Object lock = new Object();
9+
710
Thread thread = new Thread(() -> {
811
synchronized (lock) {
912
try {
1013
lock.wait();
1114
} catch (InterruptedException e) {
12-
e.printStackTrace();
15+
16+
1317
}
18+
1419
}
1520
});
21+
1622
thread.start();
23+
1724
Thread.sleep(100);
18-
System.out.println("스레드 상태: " + thread.getState()); // WAITING
25+
System.out.println("스레드 상태 : "+thread.getState());
26+
27+
// final Object lock = new Object();
28+
// Thread thread = new Thread(() -> {
29+
// synchronized (lock) {
30+
// try {
31+
// lock.wait();
32+
// } catch (InterruptedException e) {
33+
// e.printStackTrace();
34+
// }
35+
// }
36+
// });
37+
// thread.start();
38+
// Thread.sleep(100);
39+
// System.out.println("스레드 상태: " + thread.getState()); // WAITING
40+
//
1941
}
2042
}

src/main/java/io/concurrency/chapter03/exam01/BasicSleepExample.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22

33
public class BasicSleepExample {
44
public static void main(String[] args) {
5-
try {
5+
try{
66
System.out.println("2초 후에 메시지가 출력됩니다");
77
Thread.sleep(2000);
88
System.out.println("Hello World");
99

10-
} catch (InterruptedException e) {
10+
}catch (InterruptedException e){
1111
throw new RuntimeException(e);
1212
}
1313
}

src/main/java/io/concurrency/chapter03/exam01/InterruptSleepExample.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ public static void main(String[] args) throws InterruptedException {
1818

1919
sleepingThread.start();
2020

21+
//메인 스레드를 1초 정도 쉬게 한 다음
2122
Thread.sleep(1000);
22-
//
23+
24+
//메인 스레드가 sleepingThread에 대해 인터럽트 발생!!
2325
sleepingThread.interrupt();
2426
}
2527
}

src/main/java/io/concurrency/chapter03/exam01/LoopSleepExample.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ public static void main(String[] args) {
1212
throw new RuntimeException(e);
1313
}
1414
}
15-
15+
System.out.println("Thread.currentThread().getState() = " + Thread.currentThread().getState());
1616
}
1717
}

src/main/java/io/concurrency/chapter03/exam01/MultiThreadSleepExample.java

+33-6
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,22 @@
33
public class MultiThreadSleepExample {
44
public static void main(String[] args) {
55

6+
67
Thread thread1 = new Thread(() -> {
78
try {
89
System.out.println("1초 후에 메시지가 출력됩니다");
910
Thread.sleep(1000);
10-
System.out.println("스레드 1이 깨어났습니다.");
11-
11+
System.out.println("스레드 1이 깨어났습니다");
1212
} catch (InterruptedException e) {
1313
throw new RuntimeException(e);
1414
}
1515
});
1616

1717
Thread thread2 = new Thread(() -> {
1818
try {
19-
System.out.println("2초 후에 메시지가 출력됩니다");
19+
System.out.println("2초 후에 메시지가 출력 됩니다");
2020
Thread.sleep(2000);
21-
System.out.println("스레드 2가 깨어났습니다.");
22-
21+
System.out.println("스레드 2가 깨어났습니다");
2322
} catch (InterruptedException e) {
2423
throw new RuntimeException(e);
2524
}
@@ -28,7 +27,35 @@ public static void main(String[] args) {
2827
thread1.start();
2928
thread2.start();
3029

31-
System.out.println("여기는 메인입니다.");
30+
System.out.println("여기는 메인 스레드입니다");
31+
32+
33+
// Thread thread1 = new Thread(() -> {
34+
// try {
35+
// System.out.println("1초 후에 메시지가 출력됩니다");
36+
// Thread.sleep(1000);
37+
// System.out.println("스레드 1이 깨어났습니다.");
38+
//
39+
// } catch (InterruptedException e) {
40+
// throw new RuntimeException(e);
41+
// }
42+
// });
43+
//
44+
// Thread thread2 = new Thread(() -> {
45+
// try {
46+
// System.out.println("2초 후에 메시지가 출력됩니다");
47+
// Thread.sleep(2000);
48+
// System.out.println("스레드 2가 깨어났습니다.");
49+
//
50+
// } catch (InterruptedException e) {
51+
// throw new RuntimeException(e);
52+
// }
53+
// });
54+
//
55+
// thread1.start();
56+
// thread2.start();
57+
//
58+
// System.out.println("여기는 메인입니다.");
3259

3360

3461
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# InterruptSleepExample
2+
3+
```java
4+
public static void main(String[] args) throws InterruptedException {
5+
6+
Thread sleepingThread = new Thread(() -> {
7+
try {
8+
System.out.println("20초 동안 잠듭니다. 인터럽트되지 않는다면 계속 잠들어 있을 것입니다.");
9+
10+
Thread.sleep(20000); // 스레드는 지정된 시간 동안 잠듭니다
11+
12+
System.out.println("인터럽트 없이 잠에서 깨었습니다.");
13+
14+
} catch (InterruptedException e) {
15+
System.out.println("잠들어 있는 동안 인터럽트 되었습니다!");
16+
}
17+
});
18+
19+
sleepingThread.start();
20+
21+
//메인 스레드를 1초 정도 쉬게 한 다음
22+
Thread.sleep(1000);
23+
24+
//메인 스레드가 sleepingThread에 대해 인터럽트 발생!!
25+
sleepingThread.interrupt();
26+
}
27+
```
28+
- 메인 함수 내에서 실행된 Thread.sleep()은 메인 스레드를 일시 중지
29+
- 반면 스레드 객체 내에서 람다 표현식이나 익명 클래스를 통해 생성된 별도의 실행 블럭 내에서 sleep()을 걸면, 그 실행 블럭을 수행하는 스레드가 일시 중지

0 commit comments

Comments
 (0)