繁体   English   中英

从BlockingQueue读取消息时延迟

[英]Delay while reading message from BlockingQueue

我需要在从BlockingQueue读取消息时添加延迟。 当我在消费者中添加睡眠时,它不会进入睡眠模式。

制片人代码:

public void run() {
    while ((line = reader.readLine()) != null && !line.trim().isEmpty()) {
        queue.put(line);
        //queue.put(message);
    }
}

消费者代码:

public void run() {
    try {
                while((msg= queue.poll(3, TimeUnit.SECONDS)) != null && msg.getExpireTime()>=System.currentTimeMillis()) {
            System.out.println(queue.size());
            System.err.println("str = " + msg);
            Long completionTime = 0L;
            switch(msg.getMessageType()){
                case UPDATE:completionTime = 450L;break;
                case ALERT:completionTime = 250L;break;
                case REMOVE:completionTime = 100L;break;
                case ADD:completionTime = 450L;break;
            }
            log.info(msg);
            try {
                Thread.currentThread().sleep(completionTime);
            }catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Thread waiting for "+completionTime +" ms");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

输入:

first line 450ms sleep
Second Line 450ms sleep
Third Line 100ms sleep

输出:

first line 
Third Line
Third Line

预期产出:

first line 
Second Line 
Third Line

考虑使用DelayQueue .take()阻塞,直到每个元素都经过了正确的时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM