Tuesday 24 November 2015

Print Natural numbers using two Even-Odd printing Thread

Print Natural numbers using Even-Odd Thread

There are two Threads, one Thread will print the even sequence and another will print the Odd sequence.
Use these Threads to print the sequence in the natural order.

PrintOdd.java
class PrintOdd implements Runnable {
     public static boolean oddFlag = true;
     public void run() {
           for (int i = 1; i <= 9;) {
                if (oddFlag) {
                     System.out.print(i+" ");
                     oddFlag = false;
                     i = i + 2;
                }
           }
     }
}

PrintEven.java
class PrintEven implements Runnable {
     public void run() {
           for (int i = 2; i <= 10;) {
                if (!PrintOdd.oddFlag) {
                     System.out.print(i+" ");
                     PrintOdd.oddFlag = true;
                     i = i + 2;
                }
           }
     }
}

PrintNatural.java
public class PrintNatural {
     public static void main(String args[]) {
           PrintEven prEven = new PrintEven();
           PrintOdd prOdd = new PrintOdd();
           Thread evenThread = new Thread(prEven);
           Thread oddThread = new Thread(prOdd);
           evenThread.start();
           oddThread.start();
     }
}
Output:
1
2
3
4
5
6
7
8
9
10

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...