1 回答

TA貢獻2012條經驗 獲得超12個贊
這看起來是一個生產者-消費者類型的問題,我會完全不同地構造它,因為這fromClient.readLine();是阻塞的,因此應該在另一個線程中執行。
因此,考慮將另一個線程中的用戶輸入讀入數據結構,Queue<String>例如 a LinkedBlockingQueue<String>,然后每 5 秒從上述代碼中的隊列中檢索 String 元素,如果隊列中沒有元素,則不檢索任何元素。
就像是....
new Thread(() -> {
while (true) {
try {
blockingQueue.put(input.readLine());
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
try {
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
String input = blockingQueue.poll();
input = input == null ? "" : input;
toClient.println(input);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
旁注:不要調用.stop()線程,因為這是危險的事情。還要避免擴展線程。
添加回答
舉報