-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdderSubtractor.java
More file actions
57 lines (43 loc) · 1.13 KB
/
AdderSubtractor.java
File metadata and controls
57 lines (43 loc) · 1.13 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
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AdderSubtractor {
public static void main(String[] args) {
int count=0;
final Object lock=new Object();
try(ExecutorService exe= Executors.newFixedThreadPool(2)){
for (int i = 0; i < 100; i++) {
synchronized (lock){
exe.execute(new Adder(count++));
}
synchronized (lock){
exe.execute(new Subtractor(count--));
}
}
}
System.out.println(count);
System.out.println("Process done..");
}
}
class Adder implements Runnable{
int n;
public Adder(int n){
this.n=n;
}
@Override
public void run(){
n++;
System.out.println("Value incremented to "+n);
}
}
class Subtractor implements Runnable{
int sub;
public Subtractor(int sub){
this.sub=sub;
}
@Override
public void run(){
sub--;
System.out.println("Value decremented to "+sub);
}
}