第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

取消 BufferedReader 的 readLine()

取消 BufferedReader 的 readLine()

一只斗牛犬 2022-06-23 10:37:25
我寫(xiě)了一個(gè)無(wú)限循環(huán),我想每 5 秒發(fā)送一條用戶消息。因此,我編寫(xiě)了一個(gè)等待 5 秒的線程,然后發(fā)送 readLine() 方法收到的消息。如果用戶沒(méi)有提供任何輸入,則循環(huán)不會(huì)繼續(xù),因?yàn)?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貢獻(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ò)展線程。


查看完整回答
反對(duì) 回復(fù) 2022-06-23
  • 1 回答
  • 0 關(guān)注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)