Writing a program with 2 threads which prints alternatively

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

    public class PingPong extends Thread {
    static StringBuilder object = new StringBuilder("");
    
    public static void main(String[] args) throws InterruptedException {
    
        Thread t1 = new PingPong();
        Thread t2 = new PingPong();
    
        t1.setName("\nping");
        t2.setName(" pong");
    
        t1.start();
        t2.start();
    }
    
    @Override
    public void run() {
        working();
    }
    
    void working() {
        while (true) {
            synchronized (object) {
                try {
                    System.out.print(Thread.currentThread().getName());
                    object.notify();
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    }

提交回复
热议问题