×

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

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.