Odd even number printing using thread

前端 未结 13 1956
挽巷
挽巷 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:42

    I did this way

    public class OddEven{
            public static void main(String[] args){
                Print o=new Print();
                Thread even=new Thread(new MyRunnable(2,o));
                Thread odd=new Thread(new MyRunnable(1,o));
                even.start();
                odd.start();
            }
    }
    class MyRunnable implements Runnable{
            int start;
            Print ob;
            MyRunnable(int s,Print o){
                start=s;
                ob=o;
            }
            public void run(){
                for(int i=start;i<=20;i+=2)
                    ob.display(i);
            }   
    }
    class Print{
            int rem=0;
            synchronized void display(int n){
                while(n%2==rem)
                    try{
                        wait();
                    }
                    catch(Exception e){System.out.println("Display interrupted");}
                System.out.print(n+" ");
                rem=n%2;
                notify();
            }           
    }
    
    0 讨论(0)
提交回复
热议问题