Writing a program with 2 threads which prints alternatively

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

    public class Testing implements Runnable {
    private static int counter = 1;
    private static final Object lock = new Object();
    
    public static void main(String[] args)  {
    
        Thread t1 = new Thread(new Testing(), "1");
        t1.start();
        Thread t2 = new Thread(new Testing(), "2");
        t2.start();
    
    }
    
    @Override
    public void run() {
        while (counter<=100) {
            synchronized (lock) {
                if (counter % 2 == 0) {
                    System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                    counter++;
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                } else if (counter % 2 == 1) {
                    System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                    counter++;
    
                    try {
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                }
            }
        }
      }
    }
    

提交回复
热议问题