-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterthread_communication.java
More file actions
88 lines (88 loc) · 1.46 KB
/
Interthread_communication.java
File metadata and controls
88 lines (88 loc) · 1.46 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
import java.io.*;
class Thread5
{
int d;
boolean flag=false;
synchronized int getdata()
{
if(flag==false)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception Caught");
}
}
System.out.println("Got data"+d);
flag=false;
notify();
return d;
}
synchronized void putdata(int d)
{
if(flag==true)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception caught");
}
}
this.d=d;
System.out.println("Put data with value"+d);
flag=true;
notify();
}
}
class producer implements Runnable
{
Thread t;
public producer(Thread5 t)
{
this.t=t;
new Thread(this,"Producer").start();
System.out.println("put called by producer");
}
public void run()
{
int data=0;
while(true)
{
data=data+1;
t.putdata(data);
}
}
}
class consumer implements Runnable
{
Thread t;
public consumer(Thread5 t)
{
this.t=t;
new Thread(this,"consumer").start();
System.out.println("get called by consumer");
}
public void run()
{
while(true)
{
t.getdata();
}
}
}
public class Interthread_communication
{
public static void main(String args[])
{
Thread5 obj1=new Thread5();
producer p=new producer(obj1);
consumer c=new consumer(obj1);
System.out.println("press ctrl + c to stop");
}
}