Odd even number printing using thread

前端 未结 13 2015
挽巷
挽巷 2020-11-29 08:39

Odd even number printing using thread.Create one thread class, two instance of the thread. One will print the odd number and the other will print the even number.

13条回答
  •  北海茫月
    2020-11-29 09:19

    public class Number_Thread extends Thread {
    
    String thread;
    int limit;
    
    public Number_Thread(String thread,int limit){
        this.thread=thread;
        this.limit=limit;
                                                 }
    
    Object lock=new Object();
    
    public  void run()
    {
    
        synchronized (lock) 
        {
    
              //------------------- "print even"--------------------//
    
          if(thread.equals("even"))
            {
                for (int i = 2; i <=limit; i+=2) 
                {
    
                     System.out.println(thread+" thread "+i);
                try {
    
                lock.wait(1000);
                     continue;
    
                    }
                  catch (InterruptedException e) {}
                }
                lock.notifyAll();
            }
    
             //------------------- "print odd"--------------------//
    
        if(thread.equals("odd"))
             {
             for (int i = 1; i <=limit; i+=2) 
                 {
                    System.out.println(thread+" thread  "+i);
                try {
    
                    lock.wait(1000);
                        continue;
                    }
                catch (InterruptedException e) {}
                }
                lock.notifyAll();
             }
          }
       }
    }
    
         //------------------thread creater class------------------//
    import java.util.Scanner;
    
    public class Main_Thread {
    private static Scanner s;
        public static void main(String[] args) throws InterruptedException {
            System.out.print("enter limit:\t ");
            s=new Scanner(System.in);
        int n=s.nextInt();
         s.close();
        Thread t1=new Number_Thread("even",n);
        Thread t2=new Number_Thread("odd",n);
        t2.start();
        Thread.sleep(100);
        t1.start();
    
     }
    
    }
    

    output for limit 5:

    enter limit: 5

    odd thread 1

    even thread 2

    odd thread 3

    even thread 4

    odd thread 5

提交回复
热议问题