Javatpoint Logo
Javatpoint Logo

Java Program to Print Even Odd Using Two Threads in

Thread is a part of multithreading programming. In order to write a code for printing even and odd using 2 threads, it is required that we should have knowledge of multithreading.

Now, we need to print the even and odd numbers in natural order up to MAX using two different threads. So, we have two ways to solve the problem, i.e., by using wait and notify and by using the concept of the remainder.

By Using wait and notify

In order to print the even and odd numbers using wait and notify, we use the following steps:

  1. We create a boolean variable odd whose value should be true when we need to print an odd number.
  2. We create two user-defined methods such as printEventNumbers() and printOddNumbers() to print even and odd numbers.
  3. We create two threads, i.e., thread1 and thread2, for even and odd numbers simultaneously.
  4. The thread1 will call printEvenNumbers() method and the thread2 will call printOddNumbers() method simultaneously.
  5. The thread1 will wait till the value of boolean odd is true in printEvenNumbers().
  6. The thread2 will wait till the value of boolean odd is false in printOddNumbers().

Let's implement the code for printing the even odd numbers using wait and notify.

PrintEvenOddExample1.java

Output:

Java Program to Print Even Odd Using Two Threads in

By Using Remainder

In this technique of printing even and odd numbers with two threads, the code is based on the following two points:

  1. If num%2==1, odd will print the number and increment it. Else odd will go in the wait state.
  2. If number52==0, even will print the number and increment it. Else even will go in the wait state.

EvenOddRunnable.java

PrintEvenOddExample2.java

Output:

Java Program to Print Even Odd Using Two Threads in
Next TopicJava Variant





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA