Sunday, May 1, 2016

Print Odd-Even numbers in sequence using 2 Threads

Here we have used producer-consumer implementation to achieve the results.

Producer will print the even numbers starting from 0.
Consumer will print the odd numbers starting from 1.


Code:
public class MyPC {

public static void main(String[] args) {
ResourceManager rm=new ResourceManager();
Thread c=new Thread(new Consumer(rm));
Thread p=new Thread(new Producer(rm));
p.start();
c.start();

}
}

class ResourceManager{

/* This method is for consume */
public synchronized void get(){
//while not produced, we should wait for producer to produce.
//wait will release the lock and will let producer thread to execute
while(!produced){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(odd);
odd+=2;
produced=false;
notify();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
boolean produced=false;
int even=0;
int odd=1;
public synchronized void put(){
while(produced){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}

System.out.println(even);
even+=2;
produced=true;
notify();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}


class Producer implements Runnable{
ResourceManager rm;
Producer(ResourceManager r){
this.rm=r;
}
public void run(){
for(int i=0;i<10;i++){
rm.put();
}
}
}

class Consumer implements Runnable{
ResourceManager rm;
Consumer(ResourceManager r){
this.rm=r;
}
public void run(){
for(int i=0;i<10;i++){
rm.get();
}}
}

Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19


No comments:

Post a Comment