Notify not getting the thread out of wait state

前端 未结 3 1183
盖世英雄少女心
盖世英雄少女心 2021-01-28 05:28

I am trying to use 2 threads. 1 thread prints only odd number and the other thread prints only even number and It has to be an alternative operation.

Eg:



        
3条回答
  •  清歌不尽
    2021-01-28 06:08

    Modified my code based on the answer provided by Lokesh

    public class ThreadInteraction {
        public static void main(String[] args) {
            new ThreadInteraction().test();
        }
        private void test() {
            ThreadA ta = new ThreadA();
            Thread t = new Thread(ta);
            t.start();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
    
            for(int i=2;i<=50;){
                System.out.println("Thread2 "+i);
                synchronized (ta) {
                    try {
                        ta.notify();    
                        ta.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                i=i+2;
            }
        }
    }
    class ThreadA implements Runnable{
        @Override
        public void run() {
            for(int i=1;i<50;){
                System.out.println("Thread1 "+i);
                synchronized (this) {
                        try {
                            notify();                           
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                }
                i=i+2;
            }
        }
    }
    

提交回复
热议问题