栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java自定义阻塞队列的丢弃策略

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java自定义阻塞队列的丢弃策略

public class TestUtil {

	public static void main(String[] args) {
		//创建自定义长度的阻塞队列
		ArrayBlockingQueue queue = new ArrayBlockingQueue<>(5);
		//生产者1
		Thread producer = new Thread(() -> {
			try {
				for (int i = 0; i < 10; i++) {
					System.out.println("producer offer " + i);
					//添加数据
					//如添加失败,移除头数据后,再添加数据
					//丢弃过时数据
					if (!queue.offer(i)) {
						System.out.println("producer poll and offer " + i);
						queue.poll();
						queue.offer(i);
					}
					Thread.sleep(10);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});

		//生产者2-与1类似
		Thread producer1 = new Thread(() -> {
			try {
				for (int i = 20; i < 30; i++) {
					System.out.println("producer offer " + i);
					if (!queue.offer(i)) {
						System.out.println("producer poll and offer " + i);
						queue.poll();
						queue.offer(i);
					}
					Thread.sleep(10);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});

		Thread consumer = new Thread(() -> {
			try {
				while (true) {
					Thread.sleep(30);
					//消费数据
					//使用阻塞方式也可以, 但会是线程无法停止
					Integer num = queue.poll(1, TimeUnit.SECONDS);
					if (num == null) {
						break;
					}
					System.out.println("consumer poll " + num);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		//阻塞main线程
		producer.start();
		producer1.start();
		consumer.start();
		try {
			producer.join();
			producer1.join();
			consumer.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/760172.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号