Slip No 29 Q A

Write a java program using multithreading for the following:

  • Display all the odd numbers between 1 to n.
  • Display all the prime numbers between 1 to n.
import java.util.Scanner;

// Thread to display odd numbers
class OddNumbers extends Thread {
    int n;

    OddNumbers(int n) {
        this.n = n;
    }

    public void run() {
        System.out.println("Odd numbers between 1 and " + n + ":");
        for (int i = 1; i <= n; i++) {
            if (i % 2 != 0) {
                System.out.print(i + " ");
            }
        }
        System.out.println(); // for new line
    }
}

// Thread to display prime numbers
class PrimeNumbers extends Thread {
    int n;

    PrimeNumbers(int n) {
        this.n = n;
    }

    // Function to check prime
    boolean isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) return false;
        }
        return true;
    }

    public void run() {
        System.out.println("Prime numbers between 1 and " + n + ":");
        for (int i = 1; i <= n; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
        System.out.println(); // for new line
    }
}

public class MultithreadNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the value of n: ");
        int n = sc.nextInt();

        // Create threads
        OddNumbers oddThread = new OddNumbers(n);
        PrimeNumbers primeThread = new PrimeNumbers(n);

        // Start threads
        oddThread.start();
        primeThread.start();
    }
}

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top