LANGUAGE/JAVA
[JAVA] SYNCHRONIZED - 동기화
진심스테이크
2018. 3. 27. 11:53
동기화 : 멀티 스레드 프로그램에서 임계영역을 처리할 경우, 심각한 문제가 발생할 수 있는데 이를 해결할 방법
#임계영역 : 멀티 스레드에 의해 공유자원이 참조될 수 있는 코드의 범위
- 공정 처리 : 여러개의 스레드가 하나의 컴퓨팅 자원을 사용하기 위해 동시에 접근하는 프로그램을 작성 할 경우,
모든 스레드는 공정하게 그 자원을 사용할 수 있도록 함
- 기아 상태 : 하나의 동작이 독점하여 동작되는 상태 -> 공정하지 않음
-> wait( )와 notify( )를 사용하여 해결
class ATM implements Runnable {
private long depositeMoney = 10000;
public void run() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (getDepositeMoney() <= 0)
break;
withDraw(1000);
// mother과 son 둘중 하나가 독점을 막기위해 선언
this.notify(); //실행
try { //예외처리
this.wait(); //일시정지
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void withDraw(long howMuch) {
if (getDepositeMoney() > 0) {
depositeMoney -= howMuch;
System.out.print(Thread.currentThread().getName() + " , ");
System.out.println("잔액 : " + getDepositeMoney());
} else {
System.out.print(Thread.currentThread().getName() + " , ");
System.out.println("잔액이 부족합니다");
}
}
public long getDepositeMoney() {
return depositeMoney;
}
}
public class Synchronized {
public static void main(String[] args) {
ATM atm = new ATM();
Thread mother = new Thread(atm, "mother");
Thread son = new Thread(atm, "son");
mother.start();
son.start();
}
}
- 교착 상태 : 두 개 이상의 스레드가 동작을 만족하지 못할 때 발생