从BlockingQueue读取消息时延迟

时间:2013-12-05 12:56:56

标签: java multithreading

我需要在从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

1 个答案:

答案 0 :(得分:2)

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