Saturday, 8 August 2015

Program to print even and odd numbers using two threads

package JavaBuzz.Threadmania;

class PrintEvenNumbersTask implements Runnable {

private Object lock;

public PrintEvenNumbersTask(Object lock) {
    this.lock = lock;
}

@Override
public void run() {
    synchronized (lock) {
        for (int i = 0; i <= 10; i += 2) {

            lock.notify();

            System.out.println("Even : "+i);

            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        lock.notify(); // not required if thread1 gains lock first
    }
}

}


class PrintOddNumbersTask implements Runnable {

private Object lock;

public PrintOddNumbersTask(Object lock) {
    this.lock = lock;
}

@Override
public void run() {
    synchronized (lock) {
        for (int i = 1; i < 10; i += 2) {

            lock.notify();

            System.out.println("Odd : "+i);

            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        lock.notify();
    }
}

}



public class EvenOddThreads {

public static void main(String[] args) {

    Object lock = new Object();

    PrintEvenNumbersTask printEvenNumberstask = new PrintEvenNumbersTask(lock);
    PrintOddNumbersTask printOddNumberstask = new PrintOddNumbersTask(lock);

    Thread thread1 = new Thread(printEvenNumberstask);
    Thread thread2 = new Thread(printOddNumberstask);

    thread2.start();
    thread1.start();

}

}

Output : 

Odd : 1
Even : 0
Odd : 3
Even : 2
Odd : 5
Even : 4
Odd : 7
Even : 6
Odd : 9
Even : 8
Even : 10

No comments:

Post a Comment