-
Notifications
You must be signed in to change notification settings - Fork 0
/
interThreadCommunication.java
79 lines (68 loc) · 1.35 KB
/
interThreadCommunication.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
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
class Mydata
{
int value=0; // we will change the value of this property
boolean flag = true ;
synchronized public void set(int v) //set is for the producer
{
while(flag!=true)
try{wait();} catch(Exception e){}
value = v;
flag = false;
notify();
}
synchronized public int get()//get is for consumer
{
int x = 0;
while(flag!=false)
try{wait();} catch(Exception e){}
x =value;
flag = true;
notify();
return x;
}
}
class producer extends Thread
{
Mydata d;
producer(Mydata dat)
{
d = dat;
}
public void run()
{
int i =1;
while(true)
{
d.set(i);
System.out.println("producer : "+i);
i++;
}
}
}
class consumer extends Thread
{
Mydata d;
consumer(Mydata dat)
{
d = dat;
}
public void run()
{
int value;
while(true)
{
value = d.get();
System.out.println("consumer : "+value);
}
}
}
public class interThreadCommunication {
public static void main(String arg [])
{
Mydata d = new Mydata();
producer p = new producer(d);
consumer c =new consumer(d);
p.start();
c.start();
}
}