Odd even number printing using thread

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

    Here's my solution without any waits or notify. wait() and notify()/notifyAll() ,
    I dont see any reason to use them for this problem statement.

    package threading;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class EvenOddPrinting {
    
        int count=0;
        boolean isOdd = false;
    
        public static void main(String[] args) {
            ExecutorService exec = Executors.newCachedThreadPool();
            EvenOddPrinting obj = new EvenOddPrinting();
            exec.submit(new EvenPrinter(obj));
            exec.submit(new OddPrinter(obj));
            exec.shutdown();
    
    
    
        }
    
    }
    
    class EvenPrinter implements Runnable{
        EvenOddPrinting obj;
        public EvenPrinter(EvenOddPrinting obj) {
            this.obj=obj;
        }
    
        @Override
        public void run() {
            while(obj.count < 100){
                if(!obj.isOdd){
                    System.out.println("Even:"+obj.count);
                    obj.count++;
                    obj.isOdd = true;
                }
            }
    
        }
    }
    
    
    class OddPrinter implements Runnable{
    
        EvenOddPrinting obj;
        public OddPrinter(EvenOddPrinting obj) {
            this.obj = obj;
        }
    
        @Override
        public void run() {
            while(obj.count < 100){
                if(obj.isOdd){
                    System.out.println("Odd:"+obj.count);
                    obj.count++;
                    obj.isOdd = false;
                }
            }
        }
    }
    

提交回复
热议问题