Writing a program with 2 threads which prints alternatively

后端 未结 14 1590
没有蜡笔的小新
没有蜡笔的小新 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:11

    This was the simplest solution, I was able to think of. It uses a synchronized method and uses the notify() and the wait() to alternatively print the numbers. Hope it helps. :)

     public class program implements Runnable
        {
            static int count =1;
            private static final int MAX_COUNT = 50;
            public synchronized void print ()
            {
                System.out.println(Thread.currentThread().getName() + " is printing " + count);
                count++;
                notify();
                try{
                    if(count>MAX_COUNT)
                        return;
                    wait();
                }catch (InterruptedException e){ 
                    e.printStackTrace();
                }
            }
            public void run()
            {
                for(int i=0;i

提交回复
热议问题