Object Oriented Programming-I (LAB Session :- 13)


 

                                     Java Programming using Multi-threading


1.    Write a Java program to print even and odd numbers in increasing order using two threads.

a.     Create a thread to print only even numbers.

b.    Create second thread to print only odd numbers.

c.     Ask use for maximum value. Print numbers between 1 to MAX_VALUE using both threads.

CODE :
import java.util.*;
public class Tclass { 
    int counter = 1
    static int N;
    public void printOddNumber() { 
        synchronized (this)   { 
            while (counter < N) { 
                while (counter % 2 == 0) { 
                    try { 
                        wait(); 
                    } 
                    catch ( InterruptedException e) { 
                        e.printStackTrace(); 
                    } 
                } 
                System.out.print(counter + " "); 
                counter++; 
                notify(); 
            } 
        } 
    } 
    public void printEvenNumber()  { 
        synchronized (this)  { 
            while (counter < N) { 
                while (counter % 2 == 1) { 
                    try { 
                        wait(); 
                    } 
                    catch ( InterruptedException e) { 
                        e.printStackTrace(); 
                    } 
                } 
                System.out.print( counter + " ");  
                counter++; 
                notify(); 
            } 
        } 
    } 

    public static void main(String[] args)   { 
         Scanner sc= new Scanner(System.in);         
         System.out.print("Enter a number :- ");  
         N= sc.nextInt();  
         Tclass mt = new Tclass(); 
 
         System.out.println("Printing numbers between 1 to " + N +" using two threads."); 
        Thread t1 = new Thread(new Runnable() { 
            public void run()    { 
                mt.printEvenNumber(); 
            } 
        }); 
        Thread t2 = new Thread(new Runnable() { 
            public void run()    { 
                mt.printOddNumber(); 
            } 
        });      
        t1.start();
        t2.start(); 
    } 
}

OUTPUT :



No comments:

Post a Comment