由于您希望线程等待答案,我建议创建一个问题对象,其中包含问题文本,可以存储答案,并有一个CountDownLatch 用于跟踪何时有答案。
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();
}
}
然后您的工作线程可以将该问题发送到主Queue,并等待答案,例如
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);
}
}
然后主线程将使用某种BlockingQueue 来等待问题,并一次处理一个问题,例如像这样:
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);
}
}
样本输出
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]