Writing a program with 2 threads which prints alternatively

后端 未结 14 1623
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 20:47

I got asked this question recently in an interview.

Write a program with two threads (A and B), where A prints 1 , B prints 2 and so on until 50 is r

14条回答
  •  梦谈多话
    2020-12-31 21:18

    //simply use wait and notify and and set a counter and it will do  
    
    public class ThreadalternatePrint implements Runnable {
        static int counter =0; 
        @Override
        public synchronized void run() {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    
            while(counter<51)
            {   ++counter;
            notify();
            System.out.println(Thread.currentThread().getName());
                try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }       
        }
    
        public static void main(String[] args) {
            ThreadalternatePrint obj1 = new ThreadalternatePrint();
            Thread Th1 = new Thread(obj1);
            Thread Th2 = new Thread(obj1);
            Th1.setName("Thread1");
            Th2.setName("Thread2");
            Th1.start();
            Th2.start();
        }
    
    
    }
    

提交回复
热议问题