Angle Bracket <> in Java with Examples Different types of Recursions in Java Java Lambda Filter Example Java Program for Shopping Bill Pythagorean Triplet with Given Sum Using Single Loop in Java TemporalAdjusters lastInMonth() method in Java with Examples ZIP API in Java Atomic reference in Java Digit Extraction in Java DRY (Don't Repeat Yourself) Principles in Java with Examples Empty array in Java Is main method compulsory in Java? Java I/O Operation - Wrapper Class vs Primitive Class Variables Java Program to Find the Perimeter of a Rectangle Java Thread Priority Java Type Erasure Need of Concurrent Collections in Java Nested ArrayList in Java Print Odd and Even Numbers by Two Threads in Java Square pattern in Java TemporalAdjusters next() method in Java with Examples What does start() function do in multithreading in Java Convert Number to Words Problem in Java Detect And Remove Cycle in a Single Linked List in Java Evolution of Interfaces in Java How to pad a String in Java Implementing Patricia Trie in Java Java Program to Find the Most Repeated Word in a Text File java.util.UUID class in Java ReadWriteLock Interface in Java Reference Data Types in Java Sort An Array According to The Count of Set Bits in Java Alternate Vowel and Consonant string in Java Built-in Exceptions in Java with Examples Capture the Pawns Problem in Java Collections.shuffle() Method in Java with Examples JDBC MySQL Localhost 3306 Alternate Vowel and Consonant string in Java Built-in Exceptions in Java with Examples Capture the Pawns Problem in Java Collections.shuffle() Method in Java with Examples Convert Number to Words Problem in Java Detect And Remove Cycle in a Single Linked List in Java Evolution of Interfaces in Java How to pad a String in Java Implementing Patricia Trie in Java Java Program to Find the Most Repeated Word in a Text File java.util.UUID class in Java ReadWriteLock Interface in Java Reference Data Types in Java Sort An Array According to The Count of Set Bits in Java JDBC MySQL Localhost 3306 Adding a Character as Thousands Separator to Given Number in Java Circular Primes in Java Equilibrium Index Problem in Java Java String regionMatches() Method with Examples LFU Cache Problem in Java Longest Repeating and Non-Overlapping Substring in Java Prefix Suffix Search in Java Product Array Puzzle Problem in Java Russian Doll Envelopes Problem in Java Second Most Repeated Word in a Sequence in Java Special Two-Digit Numbers in a Binary Search Tree in Java Swap Corner Words and Reverse Middle Characters in Java Toggle K bits Problem in Java Upside Down Binary Tree in Java Verbal Arithmetic Puzzle Problem in Java Insert a String into another String in Java Print Shortest Path to Print a String on Screen in Java Search Insert Position in Java BST Sequences in Java Burrows - Wheeler Data Transform Algorithm in Java Convert BST to Min Heap in Java Fibonacci Sum in Java Get name of current method being executed in Java

Print Odd and Even Numbers by Two Threads in Java

In Java, it is important to create threads; one is for printing odd numbers, and the other is for even numbers in order to print both odd and even integers. We can utilize a shared object, like a printer class with synchronized methods, to make sure it is correct for synchronization and alternate printing.

What is a Thread?

An execution unit inside a program is called a thread. It allows for the concurrent execution of tasks and represents an individual flow of control. Java programs can multitask and operate in parallel because of threads.

Thread Synchronization:

In a multithreaded structure, thread synchronization in Java refers to the coordination and management of access to shared sources by various threads in order to avoid crash conditions, maintain consistency, and prevent data corruption. Several threads can use shared data concurrently in a multithreaded program. In order to avoid conflicts, synchronization makes sure that only a single thread has access to the shared resource at a time or that access happens in a controlled manner.

Inter-Thread Communication:

The techniques that many different threads utilize to coordinate, synchronize, and communicate with one another are known as inter-thread communication. In a multithreaded context, this communication is important for threads to cooperate effectively and safely.

wait(): Makes the active thread wait for an update from another thread. After releasing the lock at the object, it waits for notify() or notifyAll() to be called on the same object by another thread.

notify(): One thread that is waiting on the object gets started using the notify() function. It moves one waiting thread by notifying it, but it does not select a deterministic thread to notify.

notifyAll(): All threads waiting on the item are started up by using the notifyAll() function. Notifying various waiting threads of a change in a shared condition is a common usage for this technique.

  • Java's synchronized code blocks and methods make sure a synchronized code block or method can only executed by one thread at a time on a specific object. It is usual to combine this synchronization technique with notify(), wait(), and notifyAll().
  • Thread-safe queues, including BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue, and so on.), are available in Java by using the java.util.concurrent package. By allowing one thread to generate data and another to consume it, these queues enable communication across threads while maintaining synchronization and eliminating the need for specific wait() and notify() methods.

With the help of the above-mentioned method, the following program is written.

Filename: PrintEvenOdd.java

public class PrintEvenOdd

{

public static void main(String[] args)

{

Numbers n = new Numbers();

Thread t1 = new Thread(new OddEven(n, 12, false));

Thread t2 = new Thread(new OddEven(n, 12, true));

t1.start();

t2.start();

}

}

class OddEven implements Runnable

{

private int max;

private Numbers n;

private boolean isEven;

OddEven(Numbers n, int max, boolean isEven)

{

this.n = n;

this.max = max;

this.isEven = isEven;

}

@Override

public void run()

{

int number = isEven == true ? 2 : 1;

while (number <= max)

{

if (isEven)

{

n.Even(number);

}

else

{

n.Odd(number);

}

number += 2;

}

}

}

class Numbers

{

boolean isOdd = false;

synchronized void Even(int number)

{

while (isOdd == false)

{

try

{

wait();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

}

System.out.println("Even Number:" + number);

isOdd = false;

notifyAll();

}

synchronized void Odd(int number)

{

while (isOdd == true)

{

try

{

wait();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

}

System.out.println("Odd Number:" + number);

isOdd = true;

notifyAll();

}

}

Output:

Odd Number:1

Even Number:2

Odd Number:3

Even Number:4

Odd Number:5

Even Number:6

Odd Number:7

Even Number:8

Odd Number:9

Even Number:10

Odd Number:11

Even Number:12

Conclusion

When printing odd or even numbers in Java, two threads must be coordinated to make sure that they print odd and even numbers in return, up to a specified limit. In order to make sure that the threads are properly coordinated, this task can be completed by utilizing synchronization structures consisting of notify() and wait(). Usually, the answer involves creating threads, one for printing odd numbers and the other for even numbers.

Generally, thorough synchronization and coordination among threads are needed to achieve the expected alternating output while maintaining thread safety and appropriate access to shared resources. It is the method for printing odd and even numbers by using two threads in Java.