[Java] Synchronized 알아보기

synchronized

자바의 synchronized 키워드는 멀티 스레드 환경에서 동시 접근에 대한 간단하고 깔끔한 해결책을 제시해준다. 단, 객체 기반 락킹이라는 점만 빼면 말이다. 이 문제 때문에 자바5 이상부터 더 나은 동시성 컨트롤 방법을 담은 유틸리티 클래스들이 나타나게 되었다. 다음 코드를 실행시키면 어떤 일이 벌어지는지 충분히 이해가 갈 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class ConcurrentClass{
synchronized public void someMethod1() throws InterruptedException {
System.out.println("I am go to sleep");
Thread.sleep(5000);
System.out.println("I woke up!");
}

synchronized public void someMethod2() throws InterruptedException {
System.out.println("I am go to sleep");
Thread.sleep(5000);
System.out.println("I woke up!");
}
}

public class ConcurrentRunClass extends Thread{
protected ConcurrentClass concurrentClass = null;
protected int flag;

public ConcurrentRunClass(ConcurrentClass concurrentClass, int flag) {
this.concurrentClass = concurrentClass;
this.flag = flag;
}

public void run() {
try {
System.out.println("My flag is : " + flag);
if(flag == 1)
concurrentClass.someMethod1();
else if(flag == 2)
concurrentClass.someMethod2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class main {
public static void main(String[] args) {
ConcurrentClass concurrentClass = new ConcurrentClass();
Thread threadA = new ConcurrentRunClass(concurrentClass, 1);
Thread threadB = new ConcurrentRunClass(concurrentClass, 2);

threadA.start();
threadB.start();
}
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/13/Languages/Java/javaSynchronized/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.