Thread ODD and EVEN Printing Using Atomic Operation and Synchronization


package Thread;

import java.util.concurrent.atomic.AtomicInteger;

public class OddEvenPrint {

public static void main(String[] args) {

final Object lock= new Object();
final int max =10;
AtomicInteger number = new AtomicInteger(1);
Thread t1=new Thread(new Odd(number,max,lock));
Thread t2=new Thread(new Even(number,max,lock));
t1.start();

t2.start();


}

}

class Even extends Thread{
AtomicInteger number;
int max;
Object lock;
Even(AtomicInteger number , int max,Object lock){
this.number=number;
this.max=max;
this.lock=lock;

}


public void run(){

print1();
}


private void print1() {
while(number.get()<=max) {

if(number.get()%2==0){
System.out.println("even number : " +number.getAndIncrement());
synchronized (lock) {


lock.notifyAll();
}

}
else{
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}


}


}

class Odd extends Thread{
AtomicInteger number;
int max;
Object lock;
Odd(AtomicInteger number , int max,Object lock){
this.number=number;
this.max=max;
this.lock=lock;

}

public void run(){
print2();
}

private void print2() {
while(number.get()<=max) {

if(number.get()%2!=0){
System.out.println("odd number : " +number.getAndIncrement());
synchronized (lock) {


lock.notifyAll();
}

}
else{
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}


}

}

 


Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.
- Sandeep Kumar D

Follow Me @Google+
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment