Skip to content

Commit be4464d

Browse files
authored
Add files via upload
1 parent bb9faf8 commit be4464d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

SynchronizedDemo.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* In this example, we have two threads, threadA and threadB, that share a common object lock. threadA enters a synchronized
3+
* block, does some work, then calls lock.wait() to wait for threadB to notify it. threadB, in its synchronized block, does some work,
4+
* and then calls lock.notify() to notify threadA to resume.
5+
* When you run this code, you'll observe that threadA will wait until threadB calls lock.notify(), demonstrating how synchronization
6+
* using synchronized, wait, and notify ensures proper coordination between the two threads.
7+
*/
8+
public class SynchronizedDemo {
9+
public static void main(String[] args) {
10+
Object lock = new Object();
11+
12+
// Thread A
13+
Thread threadA = new Thread(() -> {
14+
synchronized (lock) {
15+
try {
16+
System.out.println("Thread A is doing some work.");
17+
Thread.sleep(2000);
18+
System.out.println("Thread A is waiting for Thread B to notify.");
19+
lock.wait();
20+
System.out.println("Thread A is resuming its work.");
21+
} catch (InterruptedException e) {
22+
e.printStackTrace();
23+
}
24+
}
25+
});
26+
27+
// Thread B
28+
Thread threadB = new Thread(() -> {
29+
synchronized (lock) {
30+
try {
31+
System.out.println("Thread B is doing some work.");
32+
Thread.sleep(3000);
33+
System.out.println("Thread B is notifying Thread A to resume.");
34+
lock.notify();
35+
} catch (InterruptedException e) {
36+
e.printStackTrace();
37+
}
38+
}
39+
});
40+
41+
// Start both threads
42+
threadA.start();
43+
threadB.start();
44+
45+
// Wait for both threads to finish
46+
try {
47+
threadA.join();
48+
threadB.join();
49+
} catch (InterruptedException e) {
50+
e.printStackTrace();
51+
}
52+
53+
System.out.println("Both threads have completed.");
54+
}
55+
}

0 commit comments

Comments
 (0)