Writing a program with 2 threads which prints alternatively

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

    public class ThreadCounter implements Runnable {
        private static int count = 0;
    
        private Thread t;
    
        public ThreadCounter(String tName){
            t= new Thread(this, tName);
            t.start();
        }
    
        @Override
        public void run() {
            for(int i=1; i<=5; i++){
                synchronized (CommonUtil.mLock) {
                    incrementCount(t.getName());
                    CommonUtil.mLock.notify();
                    try {
                        CommonUtil.mLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        private void incrementCount(String tName){
            System.out.println(tName+": "+(++ThreadCounter.count));
        }
    
        public static void main(String[] args) throws InterruptedException {
            new ThreadCounter("Thread1");
            Thread.sleep(500);
            new ThreadCounter("Thread2");
        }
    
    }
    
    class CommonUtil{
        public static Object mLock = new Object();
    }
    

提交回复
热议问题