0

Asynchronus consumer producer example in Java

Consumer.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
//Consumer.java
public class Consumer extends Thread
{
	private Test test;
	private int id;
 
	public Consumer(Test test, int id)
	{
		this.test = test;
		this.id = id;
	}
 
	public void run()
	{
		int k = 0;
		do
		{
			try
			{
				Thread.sleep((int)(Math.random()*1000));
			}
 
			catch(InterruptedException ie) {}
 
			k = test.getSharedInt(id);
		} while(k != 10);
	}
}

Producer.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
//Producer.java
public class Producer extends Thread //So that class behaves like a thread
{
	private Test test; //local
 
	public Producer(Test test)
	{
		this.test = test; //local pointer to external
	}
 
	public void run()
	{
		for(int k = 1; k <= 10; k++)
		{
			try
			{
				Thread.sleep((int)(Math.random()*1000));
			}
 
			catch(InterruptedException ie) {}
 
			test.setSharedInt(k); //references local address "test"
		}
	}
}

Test.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
//Test.java
public class Test
{
	private int sharedInt = 0;
	private String flag = "off";
	private Producer P = new Producer(this);
	private Consumer C1 = new Consumer(this, 1);
	private Consumer C2 = new Consumer(this, 2);
	private int servedCons = 1;
 
	public Test()
	{
		P.start();
		C1.start();
		C2.start();
	}
 
	public synchronized void setSharedInt(int x) //pass to local variable
	{
		while(flag == "on")
		{
			try
			{
				wait(); //internal flag is set and tells system to wait
			}
			catch(InterruptedException ie) {}
		}
 
		flag = "on";
		notifyAll();
 
		sharedInt = x;
		System.out.println("Setting int to " + x);
	}
 
	public synchronized int getSharedInt(int id)
	{
		while(flag == "off")
		{
			try
			{
				wait();
			}
			catch(InterruptedException ie) {}
		}
 
		if(id == servedCons)
		{
			System.out.println("Consumer " + id + sharedInt);
			servedCons++;
 
			if(servedCons == 3)
			{
				servedCons = 1;
				flag = "off";
				notifyAll();
			}
		}
 
		return sharedInt;
	}
 
	public static void main(String[] args)
	{
		Test T = new Test();
	}
}

Norbert Krupa

Technical Consultant

Leave a Reply

Your email address will not be published. Required fields are marked *