-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronizedBlock.java
More file actions
40 lines (30 loc) · 960 Bytes
/
SynchronizedBlock.java
File metadata and controls
40 lines (30 loc) · 960 Bytes
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
package Thread.Day_5;
class CountInSynchorizedBlock {
int count = 0;
void increment() {
synchronized (this) {
count++;
}
}
}
public class SynchronizedBlock {
public static void main(String[] args) throws InterruptedException {
// using Synchronized block/object
CountInSynchorizedBlock countInSynchorizedBlock = new CountInSynchorizedBlock();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
countInSynchorizedBlock.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
countInSynchorizedBlock.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("The final count in Synchronized block: " + countInSynchorizedBlock.count);
}
}