Java OCA OCP Practice Question 3144

Question

Consider the following program:

import java.util.concurrent.*;
import java.util.*;

public class Main {
        Deque<String> gangOfFour = new LinkedBlockingDeque<String>();
        class Producer extends Thread {
                String []authors = { "Java", "SQL", "Javascript", "MySQL" };
                public void run() {
                        for(String author : authors) {
                                gangOfFour.add(author);
                                try {
                                        // take time to add
                                        Thread.sleep(1000);
                                }/*www  .  j a  v a2 s .  c om*/
                                catch(InterruptedException ie) {
                                        // ignore it
                                }
                       }
               }
        }

        class Consumer extends Thread {
               int numOfAuthors = 4;
               int processedAuthors = 0;
               public void run() {
                       while(processedAuthors < 4) {
                               while (gangOfFour.isEmpty()) { /*wait till an entry is inserted*/ }

                               System.out.println(gangOfFour.remove());
                               processedAuthors++;
                       }
               }
        }

        public static void main(String []args) {
               Main blocking = new Main();
               blocking.new Producer().start();
               blocking.new Consumer().start();
        }
}

Which one of the following options correctly describes the behavior of this program?

a) Prints//from ww  w  . j a va 2 s  .co m
     Java
     and then the program terminates.
b) Prints
     Java
     SQL
     Javascript
     MySQL
     and then the program enters a deadlock and never terminates.

c) Prints
     Java
     SQL
     Javascript
     MySQL
     and then the program terminates.
d) Prints
     MySQL
     Javascript
     SQL
     Java
     and then the program terminates.
e) The program does not print any output, enters a deadlock, and never terminates.


c)

Note

The producer class puts an author on the list and then sleeps for some time.

In the meantime, the other thread (consumer) keeps checking whether the list is non-empty or not.

If it is non-empty, the consumer thread removes the item and prints it.

Hence, all four author names get printed.




PreviousNext

Related