×

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must be conversant with multithreading.Now, using two separate threads, we must print the even and odd numbers in natural order up to MAX. Therefore, we have two options for resolving the issue: employing wait and notify or the concept of the remainder.

Wait and Notify method

We employ the subsequent methods in order to print the even and odd integers using wait and notify:

1.When we want to print an odd number, we construct the boolean variable odd, whose value needs to be true.

2.To print even and odd numbers, we build two user-defined methods, printEventNumbers() and printOddNumbers().

3.For both even and odd integers, we simultaneously generate two threads, referred to as thread1 and thread2.

4.Both the printEvenNumbers() method and the printOddNumbers() method will be called simultaneously by threads 1 and 2.

5.The thread 1 will wait until printEvenNumbers' boolean odd value is true ().

6.The thread 2 will wait till the boolean odd value in printOddNumbers is false ().

Program for even and odd using Threads

EvenOdd

import java . util . Scanner ;  
  public class EvenOdd {  
    boolean odd ;  
    int c = 1 ;      
    int MAX ;  
    public void Odd ( )  {  
        synchronized ( this ) {  
            while ( c < MAX ) {  
                System . out . println ( "odd numbers  call block " ) ;  
                while ( ! odd ) {  
                    try {  
                        System . out . println ( " Odd waiting : " + c ) ;  
                        wait ( ) ;  
                        System . out . println ( " odd : " + c ) ;  
                    } catch ( InterruptedException e1 ) {  
                        e1 . printStackTrace ( ) ;  
                    }  
                }  
                System . out . println ( " Odd Thread : " + c ) ;  
                c ++ ;  
                odd = false ;  
                notify ( ) ;  
            }  
        }  
    }  
    public void Even ( ) {  
        try {  
            Thread . sleep ( 100 ) ;  
        } catch ( InterruptedException e ) {  
            e . printStackTrace ( ) ;  
        }  
        synchronized ( this ) {  
            while ( c < MAX ) {  
                System . out . println ( " even number call " ) ;  
                while ( odd ) {   
                    try {  
                        System . out . println ( " Even waiting : " + c ) ;  
                        wait ( ) ;  
                        System . out . println ( " even : " + c ) ;  
                    } catch ( InterruptedException e2 ) {  
                        e2 . printStackTrace ( ) ;  
                    }  
                }  
                System . out . println ( " Even Thread : " + c ) ;  
                 c ++ ;  
                odd = false ;  
                notify ( ) ;  
            }  
        }  
    }  
    public static void main ( String [ ] args ) {  
        final EvenOdd obj = new EvenOdd ( ) ;  
        obj . odd = true ;  
        Scanner sc = new Scanner ( System . in ) ;  
        System . out . println( " Enter MAX value : " ) ;  
        obj . MAX = sc . nextInt ( ) ;  
        sc . close ( ) ;  
        Thread t1 = new Thread ( new Runnable ( ) {  
            public void run ( ) {  
                obj . Even ( ) ;  
            }  
        } ) ;  
        Thread t2 = new Thread ( new Runnable ( ) {  
            @Override  
            public void run ( ) {  
                obj . Odd ( ) ;  
            }  
        } ) ;  
        t1 . start ( ) ;  
        t2 . start ( ) ;  
        try {  
            t1 . join ( ) ;  
            t2 . join ( ) ;  
        } catch (InterruptedException e) {  
            e . printStackTrace ( );  
        }  
    }  
}  

Output

Java Program to print even and odd numbers using 2 Threads

Method 2

// importing requied packages
public class EvenOdd { 
int counter = 1 ;
// staticvariable declaration
static int N ;
public void printOddNumber ( )
{
synchronized ( this )
{
while ( counter < N ) {
while ( counter % 2 == 0 ) {
try {
wait ( ) ;
}
catch (
InterruptedException e )  {
e . printStackTrace ( ) ;
}
}
System . out . print ( counter + " " ) ;
counter ++ ;
notify ( ) ;
}
}
}
public void printEvenNumber (  )
{
synchronized ( this )
{
while ( counter < N ) {
while ( counter % 2 == 1 ) {
// using exception handling keywords
try {
wait ( ) ;
}
catch (
InterruptedException e ) {
e . printStackTrace ( ) ;
}
}


System . out . print ( counter + " " ) ;
counter  ++ ;
notify ( ) ;
}
}
}
public static void main ( String [ ] args )
{
N = 10 ;
EvenOdd mt = new EvenOdd ( ) ;
Thread t1 = new Thread ( new Runnable ( ) {
public void run ( )
{
mt . printEvenNumber ( ) ;
}
} ) ;
Thread t2 = new Thread ( new Runnable ( ) {
public void run()
{
mt . printOddNumber ( ) ;
}
} ) ;
t1 . start ( ) ;
t2 . start ( ) ;
}
}

Output

Java Program to print even and odd numbers using 2 Threads

Related Topics

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.