Java 线程池详解

Java 线程池(Thread Pools)详解 线程池是一种重用线程的机制,用于提高线程的利用率和管理线程的生命周期,常用于多线程编程和异步编程。Java提供了多种线程池实现,其中最常用的是ThreadPoolExecutor类和Executors类提供的静态工厂方法。线程池由一个线程队列和一个任务队列组成,线程队列中保存着空闲线程,任务队列中保存着等待执行的任务。线程池启动后,线程池中的线程从任务队列中获取任务并执行,执行完毕后返回线程队列中等待下一次任务的到来。如果任务队列为空,线程池中的线程将等待新的任务到来或被关闭。 阅读详情

构造一个线程池为什么需要几个参数?如果避免线程池出现OOM?Runnable和Callable的区别是什么?本文将对这些问题一一解答,同时还将给出使用线程池的常见场景和代码片段。

基础知识

Executors创建线程池

Java中创建线程池很简单,只需要调用Executors中相应的便捷方法即可,比如Executors.newFixedThreadPool(int nThreads),但是便捷不仅隐藏了复杂性,也为我们埋下了潜在的隐患(OOM,线程耗尽)。

Executors创建线程池便捷方法列表:

方法名功能newFixedThreadPool(int nThreads)创建固定大小的线程池newSingleThreadExecutor()创建只有一个线程的线程池newCachedThreadPool()创建一个不限线程数上限的线程池,任何提交的任务都将立即执行

小程序使用这些快捷方法没什么问题,对于服务端需要长期运行的程序,创建线程池应该直接使用ThreadPoolExecutor的构造方法。没错,上述Executors方法创建的线程池就是ThreadPoolExecutor。

ThreadPoolExecutor构造方法

Executors中创建线程池的快捷方法,实际上是调用了ThreadPoolExecutor的构造方法(定时任务使用的是ScheduledThreadPoolExecutor),该类构造方法参数列表如下:

// Java线程池的完整构造函数

public ThreadPoolExecutor(

int corePoolSize, // 线程池长期维持的线程数,即使线程处于Idle状态,也不会回收。

int maximumPoolSize, // 线程数的上限

long keepAliveTime, TimeUnit unit, // 超过corePoolSize的线程的idle时长,

// 超过这个时间,多余的线程会被回收。

BlockingQueue workQueue, // 任务的排队队列

ThreadFactory threadFactory, // 新线程的产生方式

RejectedExecutionHandler handler) // 拒绝策略

竟然有7个参数,很无奈,构造一个线程池确实需要这么多参数。这些参数中,比较容易引起问题的有corePoolSize, maximumPoolSize, workQueue以及handler:

corePoolSize和maximumPoolSize设置不当会影响效率,甚至耗尽线程;

workQueue设置不当容易导致OOM;

handler设置不当会导致提交任务时抛出异常。

正确的参数设置方式会在下文给出。

线程池的工作顺序

If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.

If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.

If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.

corePoolSize -> 任务队列 -> maximumPoolSize -> 拒绝策略

Runnable和Callable

可以向线程池提交的任务有两种:Runnable和Callable,二者的区别如下:

方法签名不同,void Runnable.run(), V Callable.call() throws Exception

是否允许有返回值,Callable允许有返回值

是否允许抛出异常,Callable允许抛出异常。

Callable是JDK1.5时加入的接口,作为Runnable的一种补充,允许有返回值,允许抛出异常。

三种提交任务的方式:

提交方式是否关心返回结果Future submit(Callable task)是void execute(Runnable command)否Future submit(Runnable task)否,虽然返回Future,但是其get()方法总是返回null

如何正确使用线程池

避免使用无界队列

不要使用Executors.newXXXThreadPool()快捷方法创建线程池,因为这种方式会使用无界的任务队列,为避免OOM,我们应该使用ThreadPoolExecutor的构造方法手动指定队列的最大长度:

ExecutorService executorService = new ThreadPoolExecutor(2, 2,

0, TimeUnit.SECONDS,

new ArrayBlockingQueue<>(512), // 使用有界队列,避免OOM

new ThreadPoolExecutor.DiscardPolicy());

明确拒绝任务时的行为

任务队列总有占满的时候,这是再submit()提交新的任务会怎么样呢?RejectedExecutionHandler接口为我们提供了控制方式,接口定义如下:

public interface RejectedExecutionHandler {

void rejectedExecution(Runnable r, ThreadPoolExecutor executor);

}

线程池给我们提供了几种常见的拒绝策略:

13467292-604ddb740b1d6f57

拒绝策略拒绝行为AbortPolicy抛出RejectedExecutionExceptionDiscardPolicy什么也不做,直接忽略DiscardOldestPolicy丢弃执行队列中最老的任务,尝试为当前提交的任务腾出位置CallerRunsPolicy直接由提交任务者执行这个任务

线程池默认的拒绝行为是AbortPolicy,也就是抛出RejectedExecutionHandler异常,该异常是非受检异常,很容易忘记捕获。如果不关心任务被拒绝的事件,可以将拒绝策略设置成DiscardPolicy,这样多余的任务会悄悄的被忽略。

ExecutorService executorService = new ThreadPoolExecutor(2, 2,

0, TimeUnit.SECONDS,

new ArrayBlockingQueue<>(512),

new ThreadPoolExecutor.DiscardPolicy());// 指定拒绝策略

获取处理结果和异常

线程池的处理结果、以及处理过程中的异常都被包装到Future中,并在调用Future.get()方法时获取,执行过程中的异常会被包装成ExecutionException,submit()方法本身不会传递结果和任务执行过程中的异常。获取执行结果的代码可以这样写:

ExecutorService executorService = Executors.newFixedThreadPool(4);

Future future = executorService.submit(new Callable() {

@Override

public Object call() throws Exception {

throw new RuntimeException("exception in call~");// 该异常会在调用Future.get()时传递给调用者

}

});

try {

Object result = future.get();

} catch (InterruptedException e) {

// interrupt

} catch (ExecutionException e) {

// exception in Callable.call()

e.printStackTrace();

}

上述代码输出类似如下:

13467292-f8b239e256f47bfe

线程池的常用场景

正确构造线程池

int poolSize = Runtime.getRuntime().availableProcessors() * 2;

BlockingQueue queue = new ArrayBlockingQueue<>(512);

RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardPolicy();

executorService = new ThreadPoolExecutor(poolSize, poolSize,

0, TimeUnit.SECONDS,

queue,

policy);

获取单个结果

过submit()向线程池提交任务后会返回一个Future,调用V Future.get()方法能够阻塞等待执行结果,V get(long timeout, TimeUnit unit)方法可以指定等待的超时时间。

获取多个结果

如果向线程池提交了多个任务,要获取这些任务的执行结果,可以依次调用Future.get()获得。但对于这种场景,我们更应该使用ExecutorCompletionService,该类的take()方法总是阻塞等待某一个任务完成,然后返回该任务的Future对象。向CompletionService批量提交任务后,只需调用相同次数的CompletionService.take()方法,就能获取所有任务的执行结果,获取顺序是任意的,取决于任务的完成顺序:

void solve(Executor executor, Collection> solvers)

throws InterruptedException, ExecutionException {

CompletionService ecs = new ExecutorCompletionService(executor);// 构造器

for (Callable s : solvers)// 提交所有任务

ecs.submit(s);

int n = solvers.size();

for (int i = 0; i < n; ++i) {// 获取每一个完成的任务

Result r = ecs.take().get();

if (r != null)

use(r);

}

}

单个任务的超时时间

V Future.get(long timeout, TimeUnit unit)方法可以指定等待的超时时间,超时未完成会抛出TimeoutException。

多个任务的超时时间

等待多个任务完成,并设置最大等待时间,可以通过CountDownLatch完成:

public void testLatch(ExecutorService executorService, List tasks)

throws InterruptedException{

CountDownLatch latch = new CountDownLatch(tasks.size());

for(Runnable r : tasks){

executorService.submit(new Runnable() {

@Override

public void run() {

try{

r.run();

}finally {

latch.countDown();// countDown

}

}

});

}

latch.await(10, TimeUnit.SECONDS); // 指定超时时间

}

线程池和装修公司

以运营一家装修公司做个比喻。公司在办公地点等待客户来提交装修请求;公司有固定数量的正式工以维持运转;旺季业务较多时,新来的客户请求会被排期,比如接单后告诉用户一个月后才能开始装修;当排期太多时,为避免用户等太久,公司会通过某些渠道(比如人才市场、熟人介绍等)雇佣一些临时工(注意,招聘临时工是在排期排满之后);如果临时工也忙不过来,公司将决定不再接收新的客户,直接拒单。

线程池就是程序中的“装修公司”,代劳各种脏活累活。上面的过程对应到线程池上:

// Java线程池的完整构造函数

public ThreadPoolExecutor(

int corePoolSize, // 正式工数量

int maximumPoolSize, // 工人数量上限,包括正式工和临时工

long keepAliveTime, TimeUnit unit, // 临时工游手好闲的最长时间,超过这个时间将被解雇

BlockingQueue workQueue, // 排期队列

ThreadFactory threadFactory, // 招人渠道

RejectedExecutionHandler handler) // 拒单方式

总结

Executors为我们提供了构造线程池的便捷方法,对于服务器程序我们应该杜绝使用这些便捷方法,而是直接使用线程池ThreadPoolExecutor的构造方法,避免无界队列可能导致的OOM以及线程个数限制不当导致的线程数耗尽等问题。ExecutorCompletionService提供了等待所有任务执行结束的有效方式,如果要设置等待的超时时间,则可以通过CountDownLatch完成。

参考

ThreadPoolExecutor API Doc

Java高架构师、分布式架构、高可扩展、高性能、高并发、性能优化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战学习架构师视频免费学习加群:835638062 点击链接加入群聊【Java高级架构】:https://jq.qq.com/?_wv=1027&k=5S3kL3v

agv调度系统3.0技术介绍 agv调度系统,穿梭车调度系统,调度系统技术介绍,教你做调度 阅读详情

相关推荐

Unity获取透明物体深度数据

Unity获取透明物体深度数据前言透明&景深需求模型透明度部分带透明通道图片/视频部分半透明模型获取深度的具体实现方法带透明度图片/视频获取深度的具体实现方法结束语 前言 最近在做的项目有很多奇怪的需求,甚至之前在unity里用插件写了一个类似于蓝图的行为树插件,之后有时间给大家讲一讲相关的实现方法,今天刚解决了unity里透明物体无法获得深度数据的问题。所以分享给大家。 透明&景...

可以吃的妙脆角的博客 2632

JAVA线程池详解

最全java线程池详解,看这一篇就够了...

ZHANGLIZENG的博客 1万+

cadence allegro 17.x 降版本到16.6的转换工具

Cadence17.x版本降低到16.6版本转换工具 下载链接:Cadence17.x版本降低到16.6版本转换工具   使用方法: 软件使用比较简单,在「第一个路径输入栏」浏览指向17.x的设计文件,也就是需要降版本的17.4或者17.2的文件,然后在「第二个路径输入栏」里浏览指向转换后的文件保存路径,然后点击「转换」按钮即可。 ...

ltqdxl的博客 1万+

Java线程池最全详解

Java线程池是多线程编程中的重要工具,能够有效管理和复用线程,提高系统性能和资源利用率。本文深入探讨了线程池的基础概念、工作原理、参数配置、自定义以及使用示例,并强调了注意事项。

俺叫赵小邪的博客 4370

STC51单片机串口多字节数据接收的优化策略

本文深入探讨了STC51单片机串口多字节数据接收的优化策略。针对数据丢包、粘包等常见痛点,核心思路是采用“缓冲队列+定时器超时”模式,将实时处理转变为“先收纳,后处理”。文章详细讲解了硬件初始化、中断服务程序优化(快速入队与激活超时裁判)以及主循环的非阻塞设计,并进阶介绍了环形缓冲区实现与错误处理,旨在构建稳定可靠的串口通信系统。

weixin_29264201的博客 375

新手避坑指南:用COMSOL Multiphysics仿真气体放电(汤逊vs.流注)

本文详细介绍了使用COMSOL Multiphysics仿真气体放电的实战指南,涵盖汤逊理论和流注模型的实现方法。通过对比两种放电模型的关键参数和物理场配置,帮助新手避免常见错误,准确预测气体击穿过程。文章还提供了工程应用案例,如高压绝缘子设计优化,展示了仿真技术在电力设备绝缘设计中的实际价值。

weixin_28716181的博客 478

java线程池使用最全详解

线程池使用 前言 在执行一个异步任务或并发任务时,往往是通过直接new Thread()方法来创建新的线程,这样做弊端较多,更好的解决方案是合理地利用线程池,线程池的优势很明显,如下: 降低系统资源消耗,通过重用已存在的线程,降低线程创建和销毁造成的消耗; 提高系统响应速度,当有任务到达时,无需等待新线程的创建便能立即执行; 方便线程并发数的管控,线程若是无限制的创建,不仅会额外消耗大量系统资源,更是占用过多资源而阻塞系统或oom等状况,从而降低系统的稳定性。线程池能有效管控线程,统一分配、调优,提供资源

qq_40093255的博客 9万+

时间序列分析:ARCH、GARCH、TGARCH与DCC-GARCH波动率模型(含代码)

关注TGARCH模型和DCC-GARCH的应用,通过在沪深300和中证500指数上应用TGARCH和DCC-GARCH模型,揭示这两个指数之间的条件异方差及动态相关性的变化规律。

celiaweiwei的博客 1万+

Java线程池参数详解

线程池是现代并发编程中不可或缺的工具,合理配置线程池参数能够显著提升应用的性能和稳定性。本文将深入剖析线程池的核心参数,包括核心线程数、最大线程数、线程存活时间、任务队列类型及拒绝策略等,结合实际案例帮助读者理解每个参数的作用及调优思路。

2301_80795057的博客 2万+

因果推断三种分析框架

因果推断所涉及的三种分析框架:反事实框架CF、潜在结果模型POF和结构因果模型SCM潜在结果模型POF使用数学和可计算的语言对因果理论进行阐述,是一种将假设、命题和结论清晰化表达的计算模型,其在原因和结果变量已知的前提下定量分析原因变量对结果变量的因果效应,并对缺失的潜在结果进行补齐,使观察性研究的效果接近试验性研究. 结构因果模型SCM则是一种基于图论的因果推断方法,它将事件分 为观察、干预和反事实三个层级,并通过 do 运算将干预和反事实层级的因果关系都降维成可以通过统计学手段解决的问题.目前因果推断的

qq_46044325的博客 1829

出现 has been blocked by CORS policy: No ‘Access-Control-Allow-Origin‘ header is present on the 解决方法

Access to XMLHttpRequest at 'http://127.0.0.1:5000/api/data' from origin 'http://10.197.0.79:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

码农研究僧的博客 1万+

java线程池使用详解ThreadPoolExecutor使用示例

一 使用线程池的好处 二 Executor 框架 2.1 简介 2.2 Executor 框架结构(主要由三大部分组成) 1) 任务(Runnable /Callable) 2) 任务的执行(Executor) 3) 异步计算的结果(Future) 2.3 Executor 框架的使用示意图 三 (重要)ThreadPoolExecutor 类简单介绍 3.1 ThreadPoolExecutor 类分析 3.2 推荐使用 ThreadPoolExecutor 构造函数创建线程池 四 ..

xu_yong_lin的博客 5万+

基于STM32L4XX、HAL库的ICM-42607-P姿态传感器驱动程序设计

/ 转换为dps(±1000dps量程)float accel_x = sensor_data.accel_x * (8.0f / 32768.0f);// 转换为g值(±8g量程)#define ICM42607_I2C_ADDR 0x68 << 1 // I2C地址(SA0=0)= 0x40) { // ICM-42607的WHO_AM_I值为0x40。// 读取传感器数据。

zhusl6688的博客 835

Java 线程池原理详解

本文全面解析Java线程池的实现原理和使用方法。线程池通过复用线程、控制并发数量、任务队列管理等机制提升系统性能。核心类是ThreadPoolExecutor,包含核心线程数、最大线程数、任务队列等关键参数配置。

微笑听雨 2089

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

深度学习工具包 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")

Java线程池详解

Java线程池详解

qq_24574189的博客 1443

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

详解java线程池

前言 java 常用有线程池

u010519674的专栏 387

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

java线程池详解及五种线程池方法详解

基础知识 Executors创建线程池 Java中创建线程池很简单,只需要调用Executors中相应的便捷方法即可,比如Executors.newFixedThreadPool(int nThreads),但是便捷不仅隐藏了复杂性,也为我们埋下了潜在的隐患(OOM,线程耗尽)。 Executors创建线程池便捷方法列表: 方法名 功能 newFixedThreadPool(int nThreads) 创建固定大小的线程池 newSingleThreadExecutor()

lixiangchibang的博客 3万+

java线程池详解

一,线程池的优点 1,降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。 2,提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。 3,提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。但是要做到合理的利用线程池,必须对其原理了如指掌。 ...

MrLee的博客 1273

杂谈——Java线程池详解

在一个应用程序中,我们无可避免地需要多次使用线程,也就意味着,我们需要多次创建并销毁线程。而创建并销毁线程的过程势必会消耗内存。 举个例子,假设我们要去爬三百主流媒体网站,每天要抓一次数据,平均每次开销50毫秒,处理开销2毫秒,则可以开二十五个线程,假设每个网站有十个请求,那么三百个网站就有3000个请求。 从上面我们可以知道,CPU等待时间/CPU执行时间=25:1,这样的开销太大了,而这二...

Searchin_R的博客 4892

Java 线程池使用详解

Java 线程池使用详解

weixin_39527642的博客 433
上一篇: 大型分布式系统中的缓存架构
下一篇: 程序员都比较宅吗?
普通网友
博客等级 码龄8年 55粉丝 197原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值