java的阻塞队列blockingqueue

来源:互联网 发布:js删除数组里面空格 编辑:程序博客网 时间:2024/05/18 00:48


1、阻塞队列接口:

package com.zuk.hl.test.queue;/** * <p> Title: QueueService </p> * <p> Description: 线程安全队列 </p> * <p> Copyright: openlo.cn Copyright (C) 2017 </p> * * @author huangl * @since 2017年5月22日 上午9:54:43 */public abstract interface QueueService<T>{  public abstract boolean addToQueue(T paramT);}

2、阻塞队列实现

package com.zuk.hl.test.queue;import java.util.ArrayList;import java.util.List;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingDeque;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSON;import cn.openlo.box.BoxExecutorServiceFactory;/** * <p> Title: QueueService </p> * <p> Description: 线程安全队列实现 </p> * <p> Copyright: openlo.cn Copyright (C) 2017 </p> * * @author huangl * @since 2017年5月22日 上午9:54:43 */@Componentpublic class BlockingQueueServiceImpl implements QueueService<Person>, Runnable, InitializingBean, DisposableBean{private final Logger logger = LoggerFactory.getLogger(getClass());private static final int RecordSize = 100000;private BlockingQueue<Person> blockQueue = new LinkedBlockingDeque<Person>(RecordSize);private volatile boolean destroyed = false;/** * QueueService * */@Overridepublic boolean addToQueue(Person object){boolean b = this.blockQueue.offer(object);System.out.println("添加进入队列:"+b+",当前队列长度:"+this.blockQueue.size() + ",对象信息:"+object.toString());return b;}  /** * Runnable * */@Overridepublic void run(){while (!this.destroyed) {try{List<Person> recordList = new ArrayList();Person record = (Person)this.blockQueue.take(); //如果队列中没有数据了,则阻塞进入等待,直到队列中有数据;//System.out.print("处理:"+this.blockQueue.size());Thread.sleep(500);if(record!=null){System.out.print("处理:"+this.blockQueue.size());System.out.println(" 姓名:"+record.getName()+" age:"+record.getAge());}else{System.out.print("处理:"+this.blockQueue.size());System.out.println("null");}        if ((record instanceof StopRecord)) {System.out.println("break");break;}}catch (InterruptedException e){this.logger.info(e.getMessage(), e);throw new RuntimeException(e);}catch (Exception e){this.logger.error(e.getMessage(), e);}}}  /** * InitializingBean * */@Overridepublic void afterPropertiesSet() throws Exception{this.destroyed = false;ExecutorService service = Executors.newCachedThreadPool();service.execute(this);service.submit(this);}  /** * DisposableBean * */@Overridepublic void destroy() throws Exception{System.out.println("destroy");StopRecord stopRecord = new StopRecord();this.destroyed = true;if (this.blockQueue.size() == 0) {this.blockQueue.add(stopRecord);}}  public class StopRecord extends Person{private static final long serialVersionUID = 1L;public StopRecord() {super();}} }

3、

package com.zuk.hl.test.queue;/** * <p> Title: Person </p> * <p> Description:  </p> * <p> Copyright: openlo.cn Copyright (C) 2017 </p> * * @author huangl * @since 2017年5月22日 上午9:54:43 */public class Person {private String name;private int age; public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString(){return "{name:"+this.name+",age:"+this.age+"}";}}

4、

package zuk.hl.test.junit;import java.io.IOException;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.zuk.hl.test.queue.BlockingQueueServiceImpl;import com.zuk.hl.test.queue.Person;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:spring-context.xml")public class TestJunit {@Autowiredprivate BlockingQueueServiceImpl blockingQueueServiceImpl;@Testpublic void test() throws InterruptedException, IOException{//保持系统运行。System.out.println("进程开始:");for (int i=0;i<100;i++) {Person person = new Person();person.setAge(i);person.setName("name."+i);blockingQueueServiceImpl.addToQueue(person);//System.out.println(i);Thread.sleep(100);}System.out.println("进程结束:");//保持系统一直运行System.in.read();}}



原创粉丝点击