JAVA并发(5)-并发队列LinkedBlockingQueue的分析

并发队列之无界阻塞队列LinkedBlockingQueue 目录`LinkedBlockingQueue` 概述`LinkedBlockingQueue` 源码`LinkedBlockingQueue` 数据结构(单链表)`LinkedBlockingQueue` 主要属性 LinkedBlockingQueue 概述 LinkedBlockingQueue 来自于 jdk 1.5 的 JUC 包,是一个支持并发操作的有界阻塞队列,底层数据结构是一个单链表 作为有界队列,容量范围是{1, Integer.MAX_VALUE},可以指定容量,如果未指定容量,则默认容 阅读详情

LinkedBlockingQueue的构造器

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}

public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    // head与last指向哨兵节点
    last = head = new Node<E>(null);
}

public LinkedBlockingQueue(Collection<? extends E> c)
...

1.2 保证线程安全
LinkedBlockingQueue的底层使用ReetrantLock保证线程安全,其实就是一个"消费-生产"模型,通过本文我们还可以学到ReetrantLock的实际使用场景。

/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();

/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();

/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();

/** Wait queue for waiting puts */
private final Condition notFull = putLock.newCondition();

/**
 * Signals a waiting take. Called only from put/offer (which do not
 * otherwise ordinarily lock takeLock.)
 */
private void signalNotEmpty() {
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
}

/**
 * Signals a waiting put. Called only from take/poll.
 */
private void signalNotFull() {
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        notFull.signal();
    } finally {
        putLock.unlock();
    }
}
  1. 源码分析
    在讲LinkedBlockingQueue前,我们先看看需要它实现的接口BlockingQueue

2.1 BlockingQueue
实现了BlockingQueue的类,必须额外支持在查找元素时,等待队列直到非空为止的操作;在储存元素的时候,要等待队列的空间可用为止。
它的方法有四种形式,处理不能立即满足但是未来可能满足的操作的方式各有不同。

直接抛出异常
返回一个特殊值(null 或者 false)
一直等待,直到操作成功
超时设定,超过时间就放弃
Summary of BlockingQueue methods

我们知道了不同方法,不能立即满足的不同的处理方式,这样我们下面就更好理解LinkedBlockingQueue的源码了。

下面我们从

offer(e)
offer(e, time, unit)
put(e)
poll()
去分析一下LinkedBlockingQueue
2.2 offer(e)
添加成功就返回true; 插入值为null,报错;或队列已满,直接返回false,不会等待队列空闲

public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
// 队列的容量满了,就直接返回了
if (count.get() == capacity)
return false;
int c = -1;
Node node = new Node(e);
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
if (count.get() < capacity) {
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
}
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return c >= 0;
}
代码较简单,就不细讲了。

2.3 offer(e, time, unit)
若队列已满,还没超过设定的时间,就等待,等待时,会对中断作出反应;若超过了设定的时间,操作就跟offer(E e)一样了

public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {

    if (e == null) throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly();
    try {
        while (count.get() == capacity) {
            // 队列已满,超过了特定的时间才会返回false
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        enqueue(new Node<E>(e));
        c = count.getAndIncrement();
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return true;
}

2.4 put(e)
一直等待直到成功或者被中断

public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node node = new Node(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
// 防止虚假唤醒
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
我没有想到,上面发生虚假唤醒的场景(如果知道的同学,请告诉我一下,谢谢了)。

it is recommended that applications programmers always assume that they can occur and so always wait in a loop. --Condition

反正使用Condition在循环里等待就对了

2.5 poll()
队列为空时,直接返回null,不会await;非阻塞方法

public E poll() {
    final AtomicInteger count = this.count;
    if (count.get() == 0)
        return null;
    E x = null;
    int c = -1;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        if (count.get() > 0) {
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        }
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

其余的方法其实都是类似的,直接看上面BlockingQueue的四种方式。

最后再讲一个方法remove(Object o), 将会提及一个知识点。

2.6 remove
删除o, 若成功就返回true,反之.

public boolean remove(Object o) {
if (o == null) return false;
fullyLock();
try {
// 算法题,删除某一个链表的结点,可以看一下源码,记录两个结点,一个在前,一个在后。
for (Node trail = head, p = trail.next;
p != null;
trail = p, p = p.next) {
if (o.equals(p.item)) {
unlink(p, trail);
return true;
}
}
return false;
} finally {
fullyUnlock();
}
}
上面的代码是简单的对链表的操作,我们主要是看fullyLock() 与 fullyUnlock()的代码

/**
 * Locks to prevent both puts and takes.
 */
void fullyLock() {
    putLock.lock();
    takeLock.lock();
}

/**
 * Unlocks to allow both puts and takes.
 */
void fullyUnlock() {
    takeLock.unlock();
    putLock.unlock();
}

我们都知道解锁顺序应该与获取锁顺序相反,那么是为什么啦

其实我并不觉得,上面的fullyUnlock解锁顺序与获取锁的顺序如果是相同的会出什么问题,也并不会出现死锁(如果释放锁与获取锁,中间还存在其他操作就另当别论了)。那它仅仅是为了代码的好看?

假如,我们有下面这段代码(解锁与获取锁中间有其他操作)

A.lock();
B.lock();
Foo();
A.unlock();
Bar();
B.unlock();
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com

高并发设计核心!深度解析Java并发队列源码实现(万字长文+实战对比) Java并发队列知识图谱技术演进趋势与虚拟线程(Loom项目)的协同优化针对NUMA架构的内存访问优化与GraalVM本地化编译的结合立即行动在您的下一个项目中尝试使用不同的并发队列,观察压测数据差异,欢迎在评论区分享您的实战经验!遇到任何技术问题,也欢迎随时留言讨论~ 阅读详情

相关推荐

LinkedBlockingQueue讲解及源码解析

1.概述 自java5后,jdk增加了concurrent包,concurrent中的BlockingQueue,也就是堵塞队列,BlockingQueue只是一个接口,jdk为其提供了丰富的实现类,适用于不同的场景,这篇讲的是LinkedBlockingQueue。 2.简介 LinkedBlockingQueue继承了AbstractQueue类和实现了BlockingQueue接口,是一个基于内部链表的有界队列,如果初始化不设置大小,默认设置大小为Integer.MAX_VALUE(无界队列)。锁是基

qq_38306425的博客 3689

简单理解阻塞队列(BlockingQueue)中的take/put方法以及Condition存在的作用

简单理解阻塞队列(BlockingQueue)中的take/put方法以及Condition存在的作用 package com.zhuyz.foundation.juc; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class MyArrayBlockingQueue&lt

qq_43128724的博客 6313

USB摄像头开发实战:从参数配置到图像采集的完整流程(Python+OpenCV)

本文详细介绍了USB摄像头开发的完整流程,从参数配置到图像采集,使用Python和OpenCV实现。内容涵盖硬件原理、环境配置、参数调优及高级优化技巧,帮助开发者解决常见问题如分辨率设置、帧率控制和灯光频闪等,提升开发效率。

star的博客 244

java阻塞队列之LinkedBlockingQueue

LinkedBlockingQueue是BlockingQueue中的其中一个,其实现方式为单向链表,下面看其具体实现。(均为JDK8) 一、构造函数 在LinkedBlockingQueue中有三个构造函数,如下图, 1、LinkedBlockingQueue() 这是一个无参的构造函数,其定义如下, public LinkedBlockingQueue() { ...

weixin_33962621的博客 319

贝叶斯校准在计算机模型不确定性分析中的实践指南

本文深入探讨了贝叶斯校准在计算机模型不确定性分析中的核心原理与实践方法。通过将模型从“黑箱”转变为“透明箱”,该方法系统量化了参数不确定性、模型结构缺陷及观测误差。文章重点阐释了如何利用高斯过程作为代理模型和模型不足函数,构建完整的贝叶斯校准框架,并提供了从数据准备、模型训练到MCMC推断及不确定性分析的实战指南,最终实现更可靠的预测与决策支持。

weixin_29088655的博客 295

KALI虚拟机挂代理教程

需要你本地挂了代理,然后通过虚拟机连接本机代理端口,不说废话了,直接说怎么做了。 1.查看选项设置中自己的小飞机的本地端口是多少:(默认是1080) 2.本机win+r打开cmd,输入ipconfig查看本地ip,我的本地ip是192.168.0.107: 2.打开kali虚拟机,编辑ProxyChains配置文件: vi /etc/proxychains.conf 3.在文件末尾的ProxyList中添加物理机本地ip和1080端口作为代理地址: 4.保存并退出即可: esc :wq 回车 5.

qq_34853514的博客 3万+

java-并发集合-阻塞队列 LinkedBlockingQueue 演示

java-并发集合-阻塞队列 LinkedBlockingQueue 演示 package me.grass.demo.concuronte; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; /** * 阻塞队列 jav

草青工作室 的专栏 573

K8s入门教程(一)

本教程提供了Kubernetes(K8s)的入门指南,涵盖了从基础概念到实战操作的全面内容。首先介绍了Kubernetes的定义和核心功能,如自动化部署、弹性伸缩、自我修复等。接着,详细讲解了如何在macOS上安装Minikube和kubectl工具,以及如何使用这些工具创建和管理Pod、Deployment和Service等核心资源。教程还包括了实战案例,如部署Nginx应用,并介绍了高级特性如滚动更新和自动伸缩。最后,提供了常见问题的解决方案,帮助用户快速上手和解决实际使用中的问题。

2401_82505179的博客 1697

BlockingQueue

获取元素阻塞的方式就是通过notEmpty和notFull来进行通知,如果获取数据,队列为空这个时候notEmpty就会await()获取元素的方法线程就会等待,等到下一个线程添加元素进入到enqueue()方法就会notEmpty.signal()通知可以进行获取。如果队列满了notFull就会await(),此时这个线程就会阻塞,等到一下次别的线程获取队列元素就会通知notFull.signal(),此时获取到锁的现在就不阻塞并添加元素进队列。2、add(e),不阻塞,会抛出异常,。...

weixin_43298231的博客 254

史上最全!研究生科研必备科研工具(含AI科研工具),附使用说明和示例

这些工具在科研中的应用非常广泛,可以帮助研究生更高效地完成研究任务。为了更好地利用这些工具,建议深入学习它们的官方文档和教程,或者参加相关的工作坊和培训。

智能AI让学术科研更容易 3956

你分得清ChatGPT、Gemini、Grok、豆包、千问、DeepSeek、OpenClaw、CloudCode、vibeCodeing、sKill、MCP,飞书、微信这些到底是什么吗?

AI技术生态呈现层级化发展,从基础模型到应用平台形成完整技术栈。核心分为五层:模型层(GPT、Gemini等基础模型)→AI助手层(ChatGPT等应用产品)→工具层(ClaudeCode等开发工具)→协议层(MCP等接口标准)→应用层(微信、飞书等平台)。未来趋势将形成"模型公司-开发框架-应用生态"三层结构,AI正逐步演变为新型操作系统,通过标准化协议连接各类外部系统,实现能力调用与生态整合。技术发展呈现出从底层基础设施到上层应用场景的垂直整合特征。

hy行者勇哥的博客 408

java 常用并发队列- LinkedBlockingQueue

是 Java 中一种非常强大的并发队列实现,特别适用于需要在多线程环境中进行任务调度和缓冲的场景。它通过锁分离设计和可选的容量控制,提供了高效且安全的并发访问能力。它位于 java.util.concurrent包中,是基于链表的阻塞队列。提供了线程安全的队列操作,并且支持可选的容量限制,使其在多线程环境中的生产者-消费者模式等场景下表现出色。

Flying_Fish_roe的博客 1740

OpenClaw 2026 路线图详解:3 大协作能力升级与社区贡献增长 62% 的实证分析

介绍 OpenClaw 2026 如何通过上下文锚定(Context Anchoring)、协作质量定义和责任边界机制,将 AI 编程工具从单点补全升级为嵌入代码生命周期的协作对齐系统,并详解 `.openclaw/config.yaml` 中 `context_anchor` 配置的实操方法与效果

weixin_42545292的博客 390

[源码解析]无界阻塞队列:LinkedBlockingQueue

本篇文章是我解析Java-API的笔记,更多的是从方法着手,少对类的整体情况进行说明,故并不详尽,可供大家参考。 如果文中阐述不全或不对的,多多交流。

进步*于辰的博客 1万+

基于Java+SpringBoot+Vue的热门网游推荐系统设计与实现

本文详细介绍了基于Java+SpringBoot+Vue技术栈的热门网游推荐系统的设计与实现过程。系统采用前后端分离架构,后端使用SpringBoot构建RESTful API,前端使用Vue.js框架实现用户界面,结合MySQL数据库进行数据存储。系统实现了用户管理、游戏信息管理、个性化推荐、评论互动等核心功能,并采用了协同过滤推荐算法为用户提供个性化的游戏推荐。本文将从需求分析、系统设计、技术选型、核心功能实现以及系统测试等方面进行全面阐述。关键词:Java;SpringBoot;Vue.js;

2201_76125393的博客 78

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

高并发编程之LinkedBlockingQueue讲解

一、LinkedBlockingQueue介绍 ①、LinkedBlockingQueue是一个单向链表实现的阻塞队列,先进先出的顺序。支持多线程并发操作。相比于数组实现的ArrayBlockingQueue的有界,LinkedBlockingQueue可认为是无界队列。多用于任务队列。 ②、LinkedBlockingQueue不同于ArrayBlockingQueue,它如果不指定容量,默认为...

weixin_42146366的博客 3633

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深入理解(10)java并发之阻塞队列LinkedBlockingQueue与ArrayBlockingQueue

原文:https://blog.csdn.net/javazejian/article/details/72772461 阻塞队列概要 阻塞队列与我们平常接触的普通队列(LinkedList或ArrayList等)的最大不同点,在于阻塞队列支出阻塞添加和阻塞删除方法。 阻塞添加 所谓的阻塞添加是指当阻塞队列元素已满时,队列会阻塞加入元素的线程,直队列元素不满时才重新唤醒线程执行元素加入操作。...

cowbin2012的专栏 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

【Java】多线程和高并发编程(四):阻塞队列(中)LinkedBlockingQueue、PriorityBlockingQueue

首先PriorityBlockingQueue是一个优先级队列,他不满足先进先出的概念。会将查询的数据进行排序,排序的方式就是基于插入数据值的本身。如果是自定义对象必须要实现Comparable接口才可以添加到优先级队列排序的方式是基于二叉堆实现的。底层是采用数据结构实现的二叉堆。优先级队列PriorityBlockingQueue基于二叉堆实现的。PriorityBlockingQueue是基于数组实现的二叉堆。二叉堆是什么?二叉堆就是一个完整的二叉树。任意一个节点大于父节点或者小于父节点。

专注上位机开发、机器视觉、机器学习、嵌入式软硬件开发 1万+

Java并发阻塞队列比较:ArrayBlockingQueue、DelayQueue、LinkedBlockingDeque、LinkedBlockingQueue、LinkedTransferQue

特性边界性数据结构排序特殊特性吞吐量有界数组FIFO可选公平策略中可选有界链表FIFO默认无界高可选有界链表FIFO双端操作高无界堆排序按优先级中DelayQueue无界堆延迟基于时间获取中无容量直接传递很高无界链表FIFOtransfer()方法支持极高。

weixin_37944816的博客 907

java并发队列

在并发队列上,JDK提供了两套实现: 1. 以ConcurrentLinkedQueue为代表的高性能队列非阻塞。 2.以BlockingQueue接口为代表的阻塞队列。 无论哪种都继承自Queue。 阻塞队列与非阻塞队列 阻塞队列与非阻塞队列的区别在于: 1. 当阻塞队列是空的时,从队列中获取元素的操作将会被阻塞,试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。...

有个疙叫瘩儿的博客 2360

✅ Java并发编程:深入解析LinkedBlockingQueue

在当今的软件开发领域,高并发已经成为一个不可忽视的关键问题。尤其是在处理大量数据和高频请求的场景下,如何有效地管理并发任务,保证系统的稳定性和性能,成为了开发者必须面对的挑战。Java作为一门广泛应用于企业级应用开发的语言,提供了丰富的并发工具和类库。其中,LinkedBlockingQueue作为Java并发编程中的一种线程安全的队列实现,其在高并发场景下的应用尤为突出。

MoneyHacksPro的博客 1159

java阻塞队列LinkedBlockingQueue源码分析

一、概要 阻塞队列与我们平时接触的普通队列(LinkedList 和ArrayList)的最大的不同点,在于阻塞队列支持阻塞添加和阻塞删除方法。阻塞队列常常应用于大数据框架源码和线程池源码中。 1、阻塞添加:阻塞添加指的时当组设队列元素已经满时候。队列会阻塞加入元素的线程,直到对垒元素不满时才会重新唤醒线程执行元素加入。 2、阻塞删除:是指在队列元素为空时,删除队列元素的线程被阻塞,直到队列不为空再执行删除操作。 ArrayList 和ArrayBlockingQueue一样,内部基于数组来存放元素,而li

weixin_40809627的博客 567
上一篇: Redis(二) 数据类型操作指令以及对应的RedisTemplate方法
下一篇: MySQL Shell import_table数据导入
ting2909
博客等级 码龄7年 23粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值