wait()과 notify()에 대해 알아보자.
wait()과 notify()
현재 실행중인 쓰레드가 진행 중에 wait() 메써드를 만나면 일시적으로 정지되어 해당 쓰레드가 일시적으로 대기상태로 보내지고 제어권을 다른 쓰레드에게 넘긴다.
그리고 wait()을 만나서 대기상태에 빠진 쓰레드는 notify() 메써드를 만나면 재 구동괸다. 이런기법을 이용하면 두 개 이상의 쓰레드가 구동 중일 때 한 개의 동기화 쓰레드가 작업을 진행하면 이 작업을 완전히 마칠 때까지 기다렸다가 다른 쓰레드의 작업이 수행되는 것이 아니라, 하나의 쓰레드 동기화가 진행중일 때에도 일시적으로 해당 쓰레드를 정지시키고 다른 쓰레드가 작업을 할 수 있게 만들 수 있다.
package java12;
import java.util.Random;
import java.util.Scanner;
class Account{
int balance = 1000; // 잔액
public synchronized void withdraw(int money) {
if(balance < money ) {
try {
wait(); // 현재 쓰레드 일시 정지 => 대기 상태로 감
} catch (InterruptedException e) {
}
}
balance -= money;
}
public synchronized void deposit(int money) {
balance += money;
notify(); // 정지된 쓰레드 재실행
}
}
class AccountThread implements Runnable{
Account acc; // Account 객체 acc준비
public AccountThread(Account acc) { //생성자 정의
this.acc = acc;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
int money = (new Random().nextInt(3)+1) * 100;
// 랜덤함수는 0~1사이의 값을 반환하기 때문에 *100 해서 전수화 해줌
acc.withdraw(money);
System.out.println("잔액 : "+acc.balance);
}
}
}
public class Test06 {
public static void main(String[] args) {
Account acc =new Account();
Runnable rr = new AccountThread(acc);
Thread td = new Thread(rr);
td.start();
while(true) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
acc.deposit(n);
}
}
}

'JAVA' 카테고리의 다른 글
| [JAVA] MAP (0) | 2022.08.03 |
|---|---|
| [JAVA] Set (0) | 2022.08.02 |
| [JAVA] getter와 setter (0) | 2022.08.02 |
| [JAVA] Thread (0) | 2022.08.01 |
| [JAVA] 예외 처리 (0) | 2022.08.01 |
댓글