BlockingQueue队列实现线程池

1)BlockingQueue队列实现线程池
应用场景1:系统需要开启多线程接收日志文件,有时开启线程数过大占用内存,因此启用线程池处理接收日志。

/**
 * @ 接收日志文件,启用线程池
 * @author lim
 * @date 2017-04-01
 */
public class ReapFileThreadPool {

    private static ThreadPoolExecutor executor = 
            new ThreadPoolExecutor(10, 15, 100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());

    public static void execute(Runnable myThread){
        executor.execute(myThread);
    }

}

2)BlockingQueue实现消息队列
应用场景2:应用BlockingQueue队列实现后台数据处理进程展示,前台定时读取队列信息。

public class BlockingQueueLog {

    final static int FILE_QUEUE_SIZE = 50;// 阻塞队列大小  
    final static BlockingQueue queue = new ArrayBlockingQueue(
            FILE_QUEUE_SIZE);

    public static boolean offString(String msg){
        return queue.offer(msg);
    }

    public static List pollString(){
        List rlist = new ArrayList();
        while(true){
            Object msg = queue.poll();
            if(msg == null) break;
            rlist.add(msg);
        }
        return rlist;
    }

    public static void clearString(){
        queue.clear();
    }
} 
  

注:ArrayBlockingQueue和LinkedBlockingQueue区别
ArrayBlockingQueue实现的队列,生产者和消费锁没有分离。(适合应用场景2
LinkedBlockingQueue实现的队列,生产者和消费者的锁是分离的,所以能提高队列的并发性能。(适合应用场景1

你可能感兴趣的:(java)