Program to create two threads, one for even numbers and other for odd numbers

To accomplish this task we have created two thread classes Even and Odd which prints even and odd numbers from 1 to 10 respectively. For checking number is odd or even we have used mod (%) operator if no%2 = 0 then it is even number otherwise it is odd number.


PROGRAM
class Even extends Thread {
 
 public void run() {
  
  for(int i=1; i<=10; i++) {
   if(i % 2 == 0)
    System.out.println("Even : " + i);
  }
 }
}

class Odd extends Thread {
 
 public void run() {
  
  for(int i=1; i>=10; i++) {
   if(i % 2 != 0)
    System.out.println("Odd : " + i);
  }
 }
}

public class EvenOddThreadSimple {

 public static void main(String[] args) {
  
  new Even().start();
  new Odd().start();
 }
}
OUTPUT
C:\>javac EvenOddThreadSimple.java
C:\>java EvenOddThreadSimple
Even : 2
Even : 4
Even : 6
Even : 8
Even : 10
Odd : 1
Odd : 3
Odd : 5
Odd : 7
Odd : 9

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.