1 回答

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
這看起來(lái)是一個(gè)生產(chǎn)者-消費(fèi)者類(lèi)型的問(wèn)題,我會(huì)完全不同地構(gòu)造它,因?yàn)檫@fromClient.readLine();是阻塞的,因此應(yīng)該在另一個(gè)線程中執(zhí)行。
因此,考慮將另一個(gè)線程中的用戶輸入讀入數(shù)據(jù)結(jié)構(gòu),Queue<String>例如 a LinkedBlockingQueue<String>,然后每 5 秒從上述代碼中的隊(duì)列中檢索 String 元素,如果隊(duì)列中沒(méi)有元素,則不檢索任何元素。
就像是....
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();
旁注:不要調(diào)用.stop()線程,因?yàn)檫@是危險(xiǎn)的事情。還要避免擴(kuò)展線程。
添加回答
舉報(bào)