-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadCommunication2.java
More file actions
97 lines (85 loc) · 2.19 KB
/
ThreadCommunication2.java
File metadata and controls
97 lines (85 loc) · 2.19 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package multiThreading;
/*
* demonstration of interthread communication
* using wait() and notify() methods of the object class
* the wait() and notify() methods can be called from within a synchronized context only.
* hence either use them within a synchronized method or a synchronized block.
* the lock
* */
public class ThreadCommunication2 {
public static void main(String[] args) {
TComm tc = new TComm();
Tthread tt = new Tthread(tc);
Sthread st = new Sthread(tc);
Thread tht = new Thread(tt);
tht.start();
st.start();
}
}
class TComm {
String[] tMsg = {"hi!", "how are you?", "all the best"};
String[] sMsg = {"hello!!", "I'm fine.", "Thank You!"};
boolean flag = false;
public void t(String str) {
synchronized(this){
while (flag) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(str);
flag = true;
notify();
}
}
public synchronized void s(String str) {
while (!flag) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(str);
flag = false;
notify();
}
}
class Tthread implements Runnable {
TComm tc1 = new TComm();
public Tthread(TComm tc) {
tc1 = tc;
}
@Override
public void run() {
int size = tc1.tMsg.length;
for (int i = 0; i < size; i++) {
tc1.t(tc1.tMsg[i]);
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Sthread extends Thread {
TComm tc2 = new TComm();
public Sthread(TComm tc) {
tc2 = tc;
}
@Override
public void run() {
int size = tc2.sMsg.length;
for (int i = 0; i < size; i++) {
tc2.s(tc2.sMsg[i]);
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}