-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.java
More file actions
79 lines (69 loc) · 1.65 KB
/
Copy pathlock.java
File metadata and controls
79 lines (69 loc) · 1.65 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
class input extends Thread{
private LockedATM atm;
public input(LockedATM atm){
this.atm = atm;
}
@Override
public void run(){
atm.deposit(100);
}
}
class output extends Thread{
private LockedATM atm;
public output(LockedATM atm){
this.atm = atm;
}
@Override
public void run(){
atm.withdraw(30);
}
}
public class lock{
public static void main(String[] args){
LockedATM source = new LockedATM();
input in = new input(source);
output ou = new output(source);
in.start();
ou.start();
}
}
class LockedATM{
private Lock lock;
private int balance = 100;
public LockedATM(){
lock = new ReentrantLock();
}
public int withdraw(int value){
lock.lock();
int temp = balance;
try{
Thread.sleep(100);
temp = temp - value;
Thread.sleep(100);
balance = temp;
System.out.println("withdraw >> " + balance);
}catch(InterruptedException e){
System.out.println("error");
}
lock.unlock();
return temp;
}
public int deposit(int value){
lock.lock();
int temp = balance;
try{
Thread.sleep(100);
temp = temp + value;
Thread.sleep(50);
balance = temp;
System.out.println("deposit >> " + balance);
}catch (InterruptedException e){
System.out.println("error2");
}
lock.unlock();
return temp;
}
}