-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockWithCustomVar.java
More file actions
52 lines (40 loc) · 1.25 KB
/
LockWithCustomVar.java
File metadata and controls
52 lines (40 loc) · 1.25 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
package threadSynchronizationDemo;
public class LockWithCustomVar {
private static int counter1=0;
private static int counter2=0;
private static final Object lock1=new Object();
private static final Object lock2=new Object();
public static void main(String[] args) {
Thread one = new Thread(()->{
for (int i = 0; i < 10; i++) {
increment1();
}
});
Thread two = new Thread(()->{
for (int i = 0; i < 10; i++) {
increment2();
}
});
one.start();
two.start();
try {
one.join();
two.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(counter1 +" == "+counter2);
}
private static void increment1(){
synchronized (lock1){
counter1++;
System.out.println("Incremented counter1 to "+counter1+" using "+Thread.currentThread().getName());
}
}
private static void increment2(){
synchronized (lock2){
counter2++;
System.out.println("Incremented counter2 to "+counter2+" using "+Thread.currentThread().getName());
}
}
}