Thread Even & Odd example

Here is an example of Printing odd & even numbers using two threads. one thread will print odd & other thread will print even numbers in sequential order.


Ex.

public class EvenOdd extends Thread {                            

boolean even = false;
static AtomicInteger atint = new AtomicInteger(0);

public static void main(String args[]) {
Thread t1 = new Thread(new EvenOdd(atint));
Thread t2 = new Thread(new EvenOdd(atint));
t1.start();
t2.start();
}
public EvenOdd(AtomicInteger aint){
this.atint = aint;
}

public void run() {
while (true) {
try {
synchronized (atint) {
this.sleep(500);
if (!even) {
even = true;
show("Odd");
} else {
even = false;
show("Even");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

protected void show(String x) {

try {
int x1 = atint.addAndGet(1);
System.out.println(x + " " + x1 + "  & " + this.getName());
this.notify();
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...