Writing a program with 2 threads which prints alternatively

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

    This is another solution:

         Thread t1 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 1; i <= 50; i += 2) {
                        System.out.println("T1=" + i);
    
                        t1turn = false;
                            try {
                                lock.notifyAll();
                                lock.wait();
                            } catch (InterruptedException e) {
                            }
                    }
                }
    
            }
        });
        Thread t2 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                synchronized (lock) {
                    for (int i = 2; i <= 50; i += 2) {
                        if (t1turn)
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                            }
                        System.out.println("T2=" + i);
                        t1turn = true;
                        lock.notify();
                    }
                }
            }
        });
        t1.start();
        t2.start();
    

提交回复
热议问题