Writing a program with 2 threads which prints alternatively

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

    The essence of the assignment is to demonstrate how a thread can signal another one. Most common way is to use blocking queues, but here a signal does not carry any information, so a Semaphore is sufficient.

    Create thread class which is parameterized with 2 Semaphores: input and output:

    class ThreadPrinter implements Runnable {
        int counter;
        Semaphore ins, outs;
    
        ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
            this.counter = counter;
            this.ins = ins;
            this.outs = outs;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 25; i++) {
                ins.aquire(); // wait for permission to run
                System.out.println("" + counter);
                outs.release();  // allow another thread to run
                counter += 2;
            }
        }
    

    Create 2 Semaphores and pass them to 2 threads:

    Semaphore a = new Semaphore(1);  // first thread is allowed to run immediately
    Semaphore b = new Semaphore(0); // second thread has to wait
    ThreadPrinter tp1 = new ThreadPrinter(1, a, b);
    ThreadPrinter tp2 = new ThreadPrinter(2, b, a); 
    

    Note semaphores a and b are passed in different order.

提交回复
热议问题