Writing a program with 2 threads which prints alternatively

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

    May be this is still relevant:

    public class MyRunnable implements Runnable {
        public static int counter = 0;
        public static int turn = 0;
        public static Object lock = new Object();
    
        @Override
        public void run() {
            while (counter < 50) {
                synchronized (lock) {
                    if (turn == 0) {
    
                        System.out.println(counter + " from thread "
                                + Thread.currentThread().getName());
                        turn = 1;
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    } else {
                        turn = 0;
                        lock.notify();
                    }
    
                }
            }
        }
    }
    

    and then the main function

    public static void main(String[] args) {
            Thread threadA = new Thread(new MyRunnable());
            Thread threadB = new Thread(new MyRunnable ());
            threadA.start();
            threadB.start();
    }
    

提交回复
热议问题