由於您希望線程等待答案,我建議創建一個問題對象,其中包含問題文本,可以存儲答案,並有一個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]
我不明白廣度的原因。你能否說明理由,以便我可以照顧未來的問題? 我從Andreas得到了一個完全適合我的答案! – LearningToCode