Skip to content

Commit cdd8e17

Browse files
committed
Synchronized keyword in java
1 parent 21b43a3 commit cdd8e17

File tree

6 files changed

+55
-0
lines changed

6 files changed

+55
-0
lines changed
696 Bytes
Binary file not shown.
696 Bytes
Binary file not shown.
1.48 KB
Binary file not shown.

bin/demoVolatile/MainClass.class

0 Bytes
Binary file not shown.

bin/demoVolatile/Runner.class

0 Bytes
Binary file not shown.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package demoSynchronized;
2+
3+
public class MainClass {
4+
5+
private int count = 0;
6+
public static void main(String[] args) {
7+
MainClass mc = new MainClass();
8+
mc.startCounting();
9+
System.out.println("Count is " + mc.count);
10+
11+
}
12+
//Every object in java has an intrinsic lock (Mutex), if we call sync on the object, only one thread will acquire the lock
13+
//and other thread won't be able to acquire until the first finishes.
14+
public synchronized void increement ()
15+
{
16+
count++;
17+
}
18+
private void startCounting() {
19+
Thread t1 = new Thread(new Runnable() {
20+
@Override
21+
public void run() {
22+
for (int i=1 ; i<=1000 ;i++)
23+
{
24+
increement();
25+
}
26+
}
27+
28+
29+
});
30+
31+
Thread t2 = new Thread(new Runnable() {
32+
@Override
33+
public void run() {
34+
for (int i=1 ; i<=1000 ;i++)
35+
{
36+
increement();
37+
}
38+
}
39+
});
40+
t1.start();
41+
t2.start();
42+
43+
try {
44+
t1.join();
45+
t2.join();
46+
//join() method allows one thread to wait until another thread completes its execution.
47+
//join(): It will put the current thread on wait until the thread on which it is called is dead.
48+
//If thread is interrupted then it will throw InterruptedException.
49+
} catch (InterruptedException e) {
50+
e.printStackTrace();
51+
}
52+
}
53+
54+
55+
}

0 commit comments

Comments
 (0)