分享一段线程队列--生产者和消费者代码
2017-11-10 08:53
495 查看
分享一段线程队列--生产者和消费者代码,如有问题,请不吝赐教
import com.alibaba.fastjson.JSON; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentLinkedQueue; @Component @Scope("singleton") public class SystemLogMqSingleton { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SystemLogMqSingleton.class); private final Object notifyer = new Object(); private Thread work; private static ConcurrentLinkedQueue<Object> queue = new ConcurrentLinkedQueue<Object>(); private volatile boolean cancelled = true; private SystemLogMqSingleton() throws InterruptedException { long timeStart = System.currentTimeMillis(); work = new Thread(new Poll()); work.setName("cardbag-MqSingleton"); work.start(); if(logger.isDebugEnabled()) { logger.debug("##耗时##=======cost time " + (System.currentTimeMillis() - timeStart) + "ms"); } } /** * 生产消息 */ public void write(Object log) { queue.offer(log); } public void stop(){ cancelled=false; } /** * 消费消息 */ class Poll implements Runnable { public void run() { while (cancelled) { if (!queue.isEmpty()) { try { Object msg = queue.poll(); long startMili = System.currentTimeMillis();// 当前时间对应的毫秒数 //这里可写针对从队列里取出来的消息的处理逻辑 long endMili = System.currentTimeMillis(); if(logger.isDebugEnabled()) { logger.debug("总耗时为:" + (endMili - startMili) + "毫秒"); } } catch (Exception ex) { logger.error("================#记录数据异常#=================" + ex.getMessage() + ex.getStackTrace()); } } else { try { //如何没有消息可以等待2s,节约cpu资源 或 Thread.currentThread().sleep(2000) synchronized (notifyer) { notifyer.wait(2000); } } catch (InterruptedException e) { logger.error("##消费异常##======>"+e.getMessage()+e.getStackTrace()); e.printStackTrace(); Thread.currentThread().interrupt(); } } } } } }
相关文章推荐
- 描述消费者和生产者模式的代码(有些公司面试的时候会让你直接写一段代码)
- 线程经典代码二,(同步情况下的生产者/消费者关系)
- 面试题:用 wait-notify 写一段代码来解决生产者-消费者问题
- Java线程实现Redis任务队列(生产者消费者)
- 线程中消费者生产者的实例代码(synchronized关键字)
- Java线程同步:生产者-消费者 模型(代码示例)
- 11.python并发入门(part8 基于线程队列实现生产者消费者模型)
- Python3-线程应用队列(生产者与消费者模式--2生产者VS4消费者)
- 用生产者消费者模型实现的线程安全环形队列
- java 线程 生产者-消费者与队列,任务间使用管道进行输入、输出 讲解示例 --thinking java4
- Ruby中用线程实现经典的生产者消费者问题代码实例
- 多线程程序一段问题代码分析(生产者消费者)
- 一个线程作为生产者,一个线程作为消费者。生产者每生产一次,消费者就消费一次。生产者每次生产一定数量的商品,加上上次消费剩余的数量,而总数量不超过1000;总感觉代码不是很完善,求指教??
- Java线程同步:生产者-消费者 模型(代码示例)
- (转)一段生产者和消费者的简单多线程代码
- Python3-线程应用队列(生产者与消费者模式--多生产者VS多消费者)
- 线程经典代码一,(未同步情况下的生产者/消费者关系)
- 线程经典代码三,(循环缓冲区,生产者/消费者关系)
- java线程的wait方法和notify方法的运用(包含生产者消费者代码【已练习】)
- 线程之消费者和生产者问题代码