Skip to content

Commit e04a5fe

Browse files
committed
Mutual Exclusion
1 parent cc6715e commit e04a5fe

File tree

3 files changed

+33
-8
lines changed

3 files changed

+33
-8
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
package io.concurrency.chapter06.exam01;
2+
3+
//상호 배제 원리를 구현한 클래스
24
public class Mutex {
3-
private boolean lock = false;
4-
public synchronized void acquired() {
5-
while (lock) {
5+
private boolean lock= false;
6+
7+
public synchronized void acquired(){
8+
while(lock){
69
try {
710
wait();
811
} catch (InterruptedException e) {
9-
e.printStackTrace();
12+
throw new RuntimeException(e);
1013
}
1114
}
12-
this.lock = true;
15+
this.lock = true; //임계 영역 진입
1316
}
14-
public synchronized void release() {
17+
public synchronized void release(){
1518
this.lock = false;
16-
this.notify();
19+
this.notify(); //대기하고 있는 스레드를 깨움
1720
}
1821
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
## MutexExample
3+
4+
1. sharedData::sum를 스레드가 매개변수로 받을 수 있는 이유<br>
5+
6+
```java
7+
SharedData sharedData = new SharedData(new Mutex()); //Runnable을 구현한 클래스가 아님
8+
9+
Thread th1 = new Thread(sharedData::sum);
10+
```
11+
Thread 클래스는 Runnable 인터페이스를 받는 생성자를 제공한다<br>
12+
Runnable 인터페이스는 하나의 메서드만 있는 함수형 인터페이스로, run() 메서드를 정의한다
13+
14+
```java
15+
@FunctionalInterface
16+
public interface Runnable {
17+
void run();
18+
}
19+
```
20+
이렇게 함수형 인터페이스로 선언되어 있기 때문에 람다 표현식이나 메서드 참조를 통해 run()을 바로 구현하는 것이 가능하다
21+
22+
따라서 Thread 생성자가 이를 Runnable 인터페이스로 변환하여 내부적으로 처리하기 때문에, 굳이 Runnable을 직접 구현하지 않아도 메서드 참조를 사용해 스레드를 생성할 수 있게 되는 것!!

src/main/java/io/concurrency/chapter06/exam01/SharedData.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public void sum() {
1313
sharedValue++;
1414
}
1515

16-
} finally {
16+
} finally { //for 구문 돌다가 오류날 수 있으므로 반드시 try-finally를 통해 락을 해제해준다
1717
mutex.release(); // Lock 해제
1818
}
1919
}

0 commit comments

Comments
 (0)