-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_sync5.java
40 lines (33 loc) · 1.03 KB
/
thread_sync5.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
//Inter Thread Communication
class MyThread extends Thread {
int total;
public void run() {
System.out.println("Child Thread starts Calculation ");
synchronized (this) {
for (int i = 0; i < 5; i++) {
total = total + i;
}
System.out.println("Child Thread tries to give notification");
this.notify();
}
}
}
class Main1 {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
synchronized (t) {
try {
System.out.println("Main Thread is Waiting ");
t.wait();
System.out.println("Main Thread gets Notification..");
} catch (Exception e) {
}
}
System.out.println(t.total);
}
}
/*
This code is all about teamwork! The main thread needs the child thread to complete
its calculation before it can continue. Using wait() and notify()
lets them communicate and keeps everything running smoothly.*/