File tree 3 files changed +33
-8
lines changed
src/main/java/io/concurrency/chapter06/exam01
3 files changed +33
-8
lines changed Original file line number Diff line number Diff line change 1
1
package io .concurrency .chapter06 .exam01 ;
2
+
3
+ //상호 배제 원리를 구현한 클래스
2
4
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 ){
6
9
try {
7
10
wait ();
8
11
} catch (InterruptedException e ) {
9
- e . printStackTrace ( );
12
+ throw new RuntimeException ( e );
10
13
}
11
14
}
12
- this .lock = true ;
15
+ this .lock = true ; //임계 영역 진입
13
16
}
14
- public synchronized void release () {
17
+ public synchronized void release (){
15
18
this .lock = false ;
16
- this .notify ();
19
+ this .notify (); //대기하고 있는 스레드를 깨움
17
20
}
18
21
}
Original file line number Diff line number Diff line change
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을 직접 구현하지 않아도 메서드 참조를 사용해 스레드를 생성할 수 있게 되는 것!!
Original file line number Diff line number Diff line change @@ -13,7 +13,7 @@ public void sum() {
13
13
sharedValue ++;
14
14
}
15
15
16
- } finally {
16
+ } finally { //for 구문 돌다가 오류날 수 있으므로 반드시 try-finally를 통해 락을 해제해준다
17
17
mutex .release (); // Lock 해제
18
18
}
19
19
}
You can’t perform that action at this time.
0 commit comments