-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMethodLev_Synchronize.java
47 lines (39 loc) · 1.11 KB
/
MethodLev_Synchronize.java
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
class Counter {
private int count = 0;
// Synchronized method to increment the count
public synchronized void increment() {
count++;
}
// Synchronized method to get the current count
public synchronized int getCount() {
return count;
}
}
public class MethodLev_Synchronize {
public static void main(String[] args) {
Counter counter = new Counter();
// Creating two threads that increment the counter
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
// Starting the threads
t1.start();
t2.start();
// Waiting for threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Printing the final count
System.out.println("Final Count: " + counter.getCount());
}
}