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)
댓글 영역