java 多线程解决策略 生产者消费者模式
10192 点击·0 回帖
![]() | ![]() | |
![]() | 多线程 中一个良好的解决方案是生产者 消费者模式!
生产者消费者模式中,通常是两类线程,即很多的生产者线程和很多的消费者线程,生产线程负责提交用户请求,消费者线程负责具体处理生产者提交的任务;但是,生产者并不知道消费者的存在,也不需要,也没有需要,原因是在消费者和生产者之间有个缓冲地带,作为生产者和消费者之间的桥梁,由于这块缓存区的存在,允许生产者和消费者在执行速度上存在时间差,无论是生产者在某一句不是件内速度高于消费者,或者某一时间消费者高于生产者,起重要作用的就是这个缓冲区 private volatile boolean isRuning = false; // 内存缓存区 private BlockingQueue blockQueue; // 总数 原子操作 private static AtomicInteger count = new AtomicInteger(); // 等待时间 private static final int SLEEPTIME = 1000; // 构造方法 public Product(BlockingQueue queue) { this.blockQueue = queue; } @Override public void run() { PCData data = null; Random r = new Random(); System.out.println("start producer id=" + Thread.currentThread().getId()); while (isRuning) { try { Thread.sleep(r.nextInt(SLEEPTIME)); // 构造任务数 data = new PCData(count.incrementAndGet()); if (!blockQueue.offer(data, 20, TimeUnit.SECONDS)) { System.out.println("提交数据失败!!!!!!"); } } catch (interruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } public void stop() { isRuning = false; } public class Customer implements Runnable{ //缓冲区 private BlockingQueue customerQueue; private static final int SLEEPTIME=1000; public Customer(BlockingQueue customerQueue){ this.customerQueue=customerQueue; } @Override public void run() { System.out.println("Customer id 是:"+Thread.currentThread().getId()); Random random=new Random(); while(true){ PCData data; try { data = customerQueue.take(); if(data!=null){ int re=data.getIntData(); re=(int) Math.pow(re, 2); System.out.println(MessageFormat.format("{0}*{1}={2}", data.getIntData(),data.getIntData(),re)); Thread.sleep(random.nextInt(SLEEPTIME)); } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } } | |
![]() | ![]() |