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

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

Java如何避免在循環(huán)中使用Thread.sleep()

Java如何避免在循環(huán)中使用Thread.sleep()

千萬里不及你 2022-05-25 10:38:32
從我的主要我開始兩個(gè)線程,稱為生產(chǎn)者和消費(fèi)者。兩者都包含while(true)循環(huán)。生產(chǎn)者循環(huán)是 UDP 服務(wù)器,因此它不需要睡眠。我的問題出在消費(fèi)者循環(huán)中。消費(fèi)者循環(huán)從鏈接隊(duì)列中刪除對(duì)象并將其傳遞給函數(shù)以進(jìn)行進(jìn)一步處理。根據(jù)研究,在循環(huán)中使用線程睡眠不是一個(gè)好習(xí)慣,因?yàn)橛袝r(shí) O/S 不會(huì)在設(shè)定時(shí)間結(jié)束時(shí)釋放。如果我在應(yīng)用程序理想時(shí)刪除線程睡眠,它會(huì)將 CPU 拖到 20% 到 30%。class Producer implements Runnable {    private DatagramSocket dsocket;    FError fer = new FError();    int port =1548;    ConcurrentLinkedQueue<String> queue;    Producer(ConcurrentLinkedQueue<String> queue){        this.queue = queue;     }    @Override    public void run() {        try {            // Create a socket to listen on the port.            dsocket = new DatagramSocket(port);            // Create a buffer to read datagrams into.            byte[] buffer = new byte[30000];            // Create a packet to receive data into the buffer            DatagramPacket packet = new DatagramPacket(buffer,            buffer.length);            while (true) {                try {                   // Wait to receive a datagram                    dsocket.receive(packet);                    //Convert the contents to a string,                    String msg = new String(buffer, 0, packet.getLength());                    int ltr = msg.length();                     // System.out.println("MSG =" + msg);                    if(ltr>4)                    {                        SimpleDateFormat sdfDate = new SimpleDateFormat  ("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy                        Date now = new Date();                        String strDate = sdfDate.format(now);                        //System.out.println(strDate);                        queue.add(msg + "&" + strDate);                     // System.out.println("MSG =" + msg);                    }                  // Reset the length of the packet before reusing it.                   packet.setLength(buffer.length);                }         } 
查看完整描述

3 回答

?
飲歌長嘯

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊

而不是讓 Consumerextend Runnable你可以改變你的代碼來合并一個(gè)ScheduledExecutorService每半秒運(yùn)行一次隊(duì)列輪詢而不是讓線程休眠的代碼。這方面的一個(gè)例子是


public void schedule() {

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    executor.scheduleAtFixedRate(() -> {

        String str;

        try {

            while ((str = queue.poll()) != null) {

                call(str);  // do further processing

            }

        } catch (IOException e) {

            ferpt.felog("svr class", "consumer", "consumer thread", e.getClass().getName() + ": " + e.getMessage());

        }

    }, 0, 500, TimeUnit.MILLISECONDS);

}


查看完整回答
反對(duì) 回復(fù) 2022-05-25
?
瀟湘沐

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊

解決您的問題的正確方法是使用阻塞隊(duì)列。它為您提供了幾個(gè)優(yōu)勢:

  • 不浪費(fèi)cpu忙等待

  • 容量有限 - 假設(shè)你有一個(gè)快速的生產(chǎn)者,但一個(gè)緩慢的消費(fèi)者 -> 如果隊(duì)列的大小不受限制,那么你的應(yīng)用程序很容易達(dá)到 OutOfMemory 條件

這是一個(gè)小演示,您可以使用它:

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.BlockingQueue;


public class ProdConsTest {

    public static void main(String[] args) throws InterruptedException {

        final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

        final Runnable producer = () -> {

            for (int i = 0; i < 1000; i++) {

                try {

                    System.out.println("Producing: " + i);

                    queue.put(i);


                    //Adjust production speed by modifying the sleep time

                    Thread.sleep(100);

                } catch (InterruptedException e) {

                    //someone signaled us to terminate

                    break;

                }

            }

        };


        final Runnable consumer = () -> {

            while (true) {

                final Integer integer;

                try {

                    //Uncomment to simulate slow consumer:

                    //Thread.sleep(1000);


                    integer = queue.take();

                } catch (InterruptedException e) {

                    //someone signaled us to terminate

                    break;

                }

                System.out.println("Consumed: " + integer);

            }

        };



        final Thread consumerThread = new Thread(consumer);

        consumerThread.start();


        final Thread producerThread = new Thread(producer);

        producerThread.start();


        producerThread.join();

        consumerThread.interrupt();

        consumerThread.join();

    }

}

現(xiàn)在取消注釋sleep()消費(fèi)者并觀察應(yīng)用程序發(fā)生了什么。如果您正在使用基于計(jì)時(shí)器的解決方案,例如建議的解決方案,ScheduledExecutorService或者您正忙于等待,那么使用快速生產(chǎn)者,隊(duì)列將無法控制地增長并最終導(dǎo)致您的應(yīng)用程序崩潰


查看完整回答
反對(duì) 回復(fù) 2022-05-25
?
月關(guān)寶盒

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊

當(dāng)有新消息時(shí),讓消費(fèi)者wait()在一個(gè)對(duì)象上都可以訪問,并讓生產(chǎn)者在這個(gè)對(duì)象上監(jiān)聽。notify()然后,消費(fèi)者應(yīng)該刪除所有消息,而不僅僅是示例中的單個(gè)消息。



查看完整回答
反對(duì) 回復(fù) 2022-05-25
  • 3 回答
  • 0 關(guān)注
  • 651 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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