Writing a program with 2 threads which prints alternatively

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

    public class Test {
    
    private static int count = 0;
    
    public static void main(String[] args) throws InterruptedException {
    
        Thread t1 = new Thread(new Runnable() {
    
            @Override
            public void run() {
    
                for (int i = 0; i < 25; i++) {
                    synchronized (CommonUtil.mLock) {
                        incrementCount();
                        CommonUtil.mLock.notify();
                        try {
                            CommonUtil.mLock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
    
            @Override
            public void run() {
    
                for (int i = 0; i < 25; i++) {
                    synchronized (CommonUtil.mLock) {
                        incrementCount();
                        CommonUtil.mLock.notify();
                        try {
                            CommonUtil.mLock.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        t1.start();
        Thread.sleep(400);
        t2.start();
        t1.join();
        t2.join();
    }
    
    private static void incrementCount() {
    
        count++;
        System.out.println("Count: " + count + " icnremented by: " +        Thread.currentThread().getName());
    }
    }
      class CommonUtil {
    
     static final Object mLock = new Object();
       }
    

提交回复
热议问题