-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSynchronizedMethodAbhishek
71 lines (56 loc) · 1.51 KB
/
SynchronizedMethodAbhishek
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
package MutliThreading;
class Warehouse {
static int items = 4;
private int increment(int x) {
System.out.println("Incremented to=>" + (items + x));
items += x;
return items;
}
private int decrement(int x) {
if (items >= x) {
System.out.println("Decremented to=>" + (items - x));
items -= x;
return items;
}
return 0;
}
private void display() {
System.out.println("Total items in warehouse =>" + items);
}
synchronized void change(int x,int y) {
this.increment(x);
this.decrement(y);
this.display();
}
}
class Thread5 extends Thread {
Warehouse warehouse;
public Thread5(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
warehouse.change(5,3);
}
}
class Thread6 extends Thread {
Warehouse warehouse;
public Thread6(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
synchronized public void run() {
warehouse.change(2,4);
}
}
public class SynchronizedMethod2 {
public static void main(String[] args) throws InterruptedException {
Warehouse warehouse = new Warehouse();
Thread5 thread5 = new Thread5(warehouse);
Thread6 thread6 = new Thread6(warehouse);
thread5.start();
thread6.start();
thread6.join();
System.out.println("Finally we have " + Warehouse.items + " items in the warehouse");
}
}