Question 16
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> q = new ArrayBlockingQueue<>(2);
List<String> got = new ArrayList<>();
Thread producer = new Thread(() -> {
try { for (String s : new String[]{"o1", "o2", "o3", "o4", "STOP"}) q.put(s); } catch (InterruptedException e) { }
});
Thread consumer = new Thread(() -> {
try { for (String s; !(s = q.take()).equals("STOP"); ) got.add(s.toUpperCase()); } catch (InterruptedException e) { }
});
producer.start(); consumer.start();
producer.join(); consumer.join();
System.out.println(got + " " + q.isEmpty() + " " + q.offer("x") + q.offer("y") + q.offer("z"));
}
}
- A [O1, O2, O3, O4] true truetruefalse Correct
- B [O1, O2, O3, O4] true truetruetrue
- C [O1, O2] false truefalsefalse
- D It varies
Correct Answer: Option A
put/take block when the queue is full/empty, so no locking code is needed. offer returns false instead of blocking once the capacity of 2 is reached.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!