Print numbers in sequence using 2 Threads – Approach-2

By | May 30, 2020
  • In this post, we will learn  How to write a java program to print Even and Odd Numbers Using 2 Threads(Approach-2).
  • In the previous post, we already had seen How to Print numbers in sequence using 2 Threads
  • In this post, I have solved same problem statement with a different approach.

OddAndEvenNumberGenerator.java is used by both the threads to print odd and even numbers

OddNumberPrinter.java calls printOddNumber() method to print odd numbers

 

EvenNumberPrinter.java calls printEvenNumber() method to print even numbers

Client program SequenceNumberGeneratorTest.java 

If you run client program SequenceNumberGeneratorTest.java then this will generate below output:

Thread-1: 1
Thread-2: 2
Thread-1: 3
Thread-2: 4
Thread-1: 5
Thread-2: 6
Thread-1: 7
Thread-2: 8
Thread-1: 9
Thread-2: 10
Thread-1: 11
Thread-2: 12
Thread-1: 13
Thread-2: 14
Thread-1: 15
Thread-2: 16
Thread-1: 17
Thread-2: 18
Thread-1: 19
Thread-2: 20

 

You May Also Like:

Difference between List and Set in Java Collection ?
When should we choose LinkedList over ArrayList for a given Scenario and Why?
Is there concurrent version for TreeMap and TreeSet in Java Collections Framework?
What is difference between Collections. Sort() and Arrays.sort()? Which one is better with respect to time efficiency?
What are fail-fast and fail-safe Iterator?
What is difference between Iterator and LisIterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?
What all collections utilizes hashCode() method in java?
Describe CopyOnWriteArrayList? Where is it used in Java Applications?

That’s all about Print numbers in sequence using 2 Threads – Approach-2
If you have any feedback or suggestion please feel free to drop in below comment box. 

Leave a Reply

Your email address will not be published.