Since you want the thread to wait for an answer, I’d suggest creating a question object that has the question text, can store the answer, and has a CountDownLatch
for tracking when the answer is available.
public final class Question {
private final String question;
private String answer;
private CountDownLatch latch = new CountDownLatch(1);
public Question(String question) {
this.question = question;
}
public String getQuestion() {
return this.question;
}
public String getAnswer() throws InterruptedException {
this.latch.await();
return this.answer;
}
public void setAnswer(String answer) {
this.answer = answer;
this.latch.countDown();
}
}
Your worker thread can then send that question to the main Queue
, and wait for the answer, e.g.
public final class Worker implements Runnable {
private final Queue<Question> queue;
private final int delayInSeconds;
private final String[] questions;
public Worker(Queue<Question> queue, int delayInSeconds, String... questions) {
this.queue = queue;
this.delayInSeconds = delayInSeconds;
this.questions = questions;
}
@Override
public void run() {
List<String> answers = new ArrayList<>();
try {
for (String question : this.questions) {
Thread.sleep(this.delayInSeconds * 1000L);
Question q = new Question(question);
this.queue.add(q);
String answer = q.getAnswer();
answers.add(answer);
}
} catch (InterruptedException unused) {
System.out.println("Interrupted");
}
System.out.println(answers);
}
}
The main thread would then use some kind of BlockingQueue
to wait for questions, and to process them one at a time, e.g. like this:
public static void main(String[] args) throws Exception {
BlockingQueue<Question> queue = new LinkedBlockingQueue<>();
Worker w1 = new Worker(queue, 3, "Can you play poker?",
"Can you juggle?",
"Can you summersault?");
Worker w2 = new Worker(queue, 4, "How old are you?",
"How tall are you?");
new Thread(w1).start();
new Thread(w2).start();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
Question q = queue.take();
System.out.println(q.getQuestion());
String answer = in.nextLine();
q.setAnswer(answer);
}
}
Sample output
Can you play poker?
yes
How old are you?
13
Can you juggle?
no
How tall are you?
5 11
Can you summersault?
[13, 5 11]
no
[yes, no, no]
1
solved Suggest data-structure for this use case [closed]