亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

取消 BufferedReader 的 readLine()

取消 BufferedReader 的 readLine()

一只斗牛犬 2022-06-23 10:37:25
我寫了一個無限循環,我想每 5 秒發送一條用戶消息。因此,我編寫了一個等待 5 秒的線程,然后發送 readLine() 方法收到的消息。如果用戶沒有提供任何輸入,則循環不會繼續,因為 readLine() 方法正在等待輸入。那么如何取消 readLine() 方法呢?while (true) {        new Thread() {            @Override            public void run() {                try {                    long startTime = System.currentTimeMillis();                    while ((System.currentTimeMillis() - startTime) < 5000) {                    }                    toClient.println(serverMessage);                    clientMessage = fromClient.readLine();                    System.out.println(clientName + ": " + clientMessage);                } catch (IOException e) {                    e.printStackTrace();                }            }        }.start();        serverMessage = input.readLine();    }
查看完整描述

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()線程,因為這是危險的事情。還要避免擴展線程。


查看完整回答
反對 回復 2022-06-23
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號