Print Odd and Even Numbers Using Threads And Semaphore

By | June 1, 2020

Hello Friends,
In this post, we will talk and learn about How to Write a Java program Print Odd and Even Numbers Using Threads And Semaphore.

Here Idea is that Thread-1 has to print Odd numbers and Thread-2 has to print Even numbers in Sequential order as below:

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

 

Resource OddAndEvenNumberGenerator.java is going to share with both the Threads to print odd and even numbers.

Source code of OddNumberGenerator.java and EvenNumberGenerator.java 

OddEvenNumberPrintByTwoThreadsTest.Java Client program with main Method:

If you run  OddEvenNumberPrintByTwoThreadsTest.Java then we get 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:

Understating of Polymorphism in Java
Method Overloading or Static Polymorphism in Java
Method Overriding or Dynamic Polymorphism in Java
Understating of Inheritance in Java
Difference Between Encapsulation and Abstraction in Java
Association Aggregation And Composition in Java

That’s all about How to Print Odd and Even Numbers Using Threads And Semaphore ?
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. Required fields are marked *