Amazon Prime




 
Tagged
  • Java
  • Java Multithreading
  •  

    Java program to print Odd Even Numbers Using Two Threads and Semaphore

    In this tutorial, we will learn to print odd and even numbers sequentially using two threads. Like odd thread should print odd numbers and even thread should print even numbers in sequential order. For this two threads should communicate with each other which is called inter-thread communication

    Code Implementation

    1import java.util.concurrent.Semaphore;
    2
    3public class OddEvenPrinterUsingSemaphore {
    4
    5 Semaphore evenSemaphore = new Semaphore(0);
    6 Semaphore oddSemaphore = new Semaphore(1);
    7
    8 public static void main(String[] args) {
    9 int max = 20;
    10 OddEvenPrinterUsingSemaphore obj = new OddEvenPrinterUsingSemaphore();
    11 Thread t1 = new Thread(() -> {
    12 for (int i = 1; i <= max; i = i + 2) {
    13 obj.printOdd(i);
    14 }
    15 }, "T1");
    16 Thread t2 = new Thread(() -> {
    17 for (int i = 2; i <= max; i = i + 2) {
    18 obj.printEven(i);
    19 }
    20 }, "T2");
    21
    22 t1.start();
    23 t2.start();
    24 }
    25
    26 public void printOdd(int number) {
    27 try {
    28 oddSemaphore.acquire();
    29 } catch (InterruptedException e) {
    30 e.printStackTrace();
    31 }
    32 System.out.println(Thread.currentThread().getName() + " : " + number);
    33 evenSemaphore.release();
    34 }
    35
    36 public void printEven(int number) {
    37 try {
    38 evenSemaphore.acquire();
    39 } catch (InterruptedException e) {
    40 e.printStackTrace();
    41 }
    42 System.out.println(Thread.currentThread().getName() + " : " + number);
    43 oddSemaphore.release();
    44 }
    45}

     

  • Java
  • Java Multithreading
  •  
    ...