场景:
防止接收数据时处理不过来导致阻塞,使用ArrayBlockingQueue队列存储数据后,以多线程的方式处理数据 保证系统性能。
package com.yl.demo.main4;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** @author YL* 使用java自带的队列进行存取数据*/
public class Test {public static void main(String[] args) {//创建队列ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(100);//创建线程ExecutorService executorService = Executors.newFixedThreadPool(10);//让十个线程动起来将数据存入队列for (int i = 0; i < 10; i++) {//执行线程executorService.submit(() -> {//格式化时间SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");//当前时间存入队列arrayBlockingQueue.add(simpleDateFormat.format(new Date()));});}//一直启动线程while (true) {//十个线程全部启用for (int i = 0; i < 10; i++) {//执行线程executorService.submit(() -> {try {//阻塞读取队列 队列有值则进行读取String take = arrayBlockingQueue.take();//输出System.out.println("take = " + take);} catch (InterruptedException e) {throw new RuntimeException(e);}});}}}
}