Problem Statement: How will print Odd Even using Thread?
OR
How will you print t1 & t2 alternatively using thread?
- import java.util.concurrent.atomic.AtomicLong;
- class Even extends Thread {
- AtomicLong num;
- Object lock;
- Even(AtomicLong num, Object lock) { // constructor
- this.num = num;
- this.lock = lock;
- }
- public void run() {
- synchronized (lock) {
- while (true) { // infinite loop
- if (num.get() % 2 != 0) {
- try {
- lock.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("even: " + num);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- num.incrementAndGet();
- lock.notifyAll();
- }
- }
- }
- }
- } // end of Even class
- class Odd extends Thread {
- AtomicLong num;
- Object lock;
- Odd(AtomicLong num, Object lock) { // constructor
- this.num = num;
- this.lock = lock;
- }
- public void run() {
- synchronized (lock) {
- while (true) { // infinite loop
- if (num.get() % 2 == 0) {
- try {
- lock.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("odd: " + num);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- num.incrementAndGet();
- lock.notifyAll();
- }
- }
- }
- }
- } // end of Odd class
- public class EvenOddByThread {
- public static void main(String[] args) {
- AtomicLong num = new AtomicLong(1);
- Object lock = new Object();
- Odd odd = new Odd(num, lock);
- Even even = new Even(num, lock);
- even.start();
- odd.start();
- }
- } // end of EvenOddByThread class
Note: To print t1 & t2 alernatively, just replace the S.O.P. stmt with t1 & t2
Output:
odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
odd: 9
even: 10
No comments:
Post a Comment