Writing a program with 2 threads which prints alternatively

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

    package thread;
    
    public class Pingpong extends Thread {
        static StringBuilder object = new StringBuilder("");
        static int i=1;
    
        @Override
        public void run() {
            working();
        }
        void working() {
            while (i<=10) {
                synchronized (object) {
                    try {
                        System.out.println(Thread.currentThread().getName() +"  "+ i);
                        i++;
                        object.notify();
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Pingpong();
            Thread t2 = new Pingpong();
            t1.setName("Thread1");
            t2.setName("Thread2");
            t1.start();
            t2.start();
        }
    }
    
    Thread1  1
    Thread2  2
    Thread1  3
    Thread2  4
    Thread1  5
    Thread2  6
    Thread1  7
    Thread2  8
    Thread1  9
    Thread2  10
    

提交回复
热议问题