상세 컨텐츠

본문 제목

[운영체제] Lock을 이용한 동시성 제어

CS구멍/운영체제🐣

by :Eundms 2024. 10. 15. 13:26

본문

public class LockedATMMain {

	public static void main(String[] args) {
		LockedATM atm = new LockedATM();
		LockedATMThread thread1 = new LockedATMThread(atm, "deposit", 1000);
		thread1.start();

		LockedATMThread thread2 = new LockedATMThread(atm, "withdraw", 10000);
		thread2.start();
        
	}
}
public class LockedATMThread extends Thread {
	private LockedATM lockedAtm;
	private String type;
	private int value;

	public LockedATMThread(LockedATM lockedAtm, String type, int value) {
		this.lockedAtm = lockedAtm;
		this.type = type;
		this.value = value;
	}

	public void run() {
		if (type.equals("deposit")) {
			lockedAtm.deposit(value);
		} else {
			lockedAtm.withdraw(value);
		}
	}

}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockedATM {
	private Lock lock;
	private int balance = 100;

	public LockedATM() {
		lock = new ReentrantLock();
	}

	public int withdraw(int value) {
		lock.lock();
		System.out.println("Withdraw(-): prev(" + this.balance + ") minus " + value);

		int temp = balance;
		try {
			Thread.sleep(3);
			temp = temp - value;
			Thread.sleep(3);
			balance = temp;
		} catch (InterruptedException e) {
		}
		System.out.println("Withdraw(-): after(" + this.balance + ")");

		lock.unlock();
		return temp;
	}

	public int deposit(int value) {
		lock.lock();
		System.out.println("Deposit(+): prev(" + this.balance + ") add value " + value);

		int temp = balance;
		try {
			Thread.sleep(100);
			temp = temp + value;
			Thread.sleep(300);
			balance = temp;
		} catch (InterruptedException e) {
		}
		System.out.println("Deposit(+): after(" + this.balance + ")");

		lock.unlock();

		return temp;

	}
}

정상적인 결과

Deposit(+): prev(100) add value 1000
Deposit(+): after(1100)
Withdraw(-): prev(1100) minus 10000
Withdraw(-): after(-8900)

이상현상

Withdraw(-): prev(100) minus 10000
Deposit(+): prev(100) add value 1000
Withdraw(-): after(-9900)
Deposit(+): after(1100)
728x90

'CS구멍 > 운영체제🐣' 카테고리의 다른 글

[운영체제] 프로세스 생성  (0) 2024.11.05
[운영체제] 8. 스레드  (0) 2021.03.23
[운영체제] 2. Process  (0) 2021.03.17

관련글 더보기

댓글 영역