深入浅出吃透多线程、线程池核心原理及代码详解

C++—线程池(附源代码) std::atomic 提供了原子操作,适用于需要在多线程环境中进行无锁操作的场景。std::atomic_flag 用于实现低级别的锁机制,如自旋锁。了解内存序是使用原子操作时的一个重要方面,它帮助你控制操作的顺序和可见性,从而确保程序的正确性和效率。 阅读详情

一、多线程详解

  1、什么是线程

  线程是一个操作系统概念。操作系统负责这个线程的创建、挂起、运行、阻塞和终结操作。而操作系统创建线程、切换线程状态、终结线程都要进行CPU调度——这是一个耗费时间和系统资源的事情。

腾讯认证T9后端开发岗位,linux服务器开发高级架构师系统学习视频点击:C/C++Linux服务器开发高级架构师/Linux后台架构师

B站7000+播放的线程池视频讲解:150行代码,手写线程池(完整版)

  2、线程生命周期

 线程通常都有五种状态,创建、就绪、运行、阻塞和死亡:

  • 创建状态。在生成线程对象,并没有调用该对象的start方法,这是线程处于创建状态。
  • 就绪状态。当调用了线程对象的start方法之后,该线程就进入了就绪状态,但是此时线程调度程序还没有把该线程设置为当前线程,此时处于就绪状态。在线程运行之后,从等待或者睡眠中回来之后,也会处于就绪状态。
  • 运行状态。线程调度程序将处于就绪状态的线程设置为当前线程,此时线程就进入了运行状态,开始运行run函数当中的代码。
  • 阻塞状态。线程正在运行的时候,被暂停,通常是为了等待某个时间的发生(比如说某项资源就绪)之后再继续运行。sleep,suspend,wait等方法都可以导致线程阻塞。
  • 死亡状态。如果一个线程的run方法执行结束或者调用stop方法后,该线程就会死亡。对于已经死亡的线程,无法再使用start方法令其进入就绪。   

  可以用过jstack 或者idea debug快照显示状态,常见名词大致意思为:

  • "Low Memory Detector":负责对可使用内存进行检测,如果发现可用内存低,分配新的内存空间。
  • "CompilerThread0":用来调用JITing,实时编译装卸class。
  • "Signal Dispatcher":负责分发内部事件。
  • "Finalizer":负责调用Finalizer方法。
  • "Reference Handler":负责处理引用。
  • "main":是主线程。
  • "VM Thread", "VM Periodic Task Thread":从名字上看是虚机内部线程。

  3、线程状态描述

  • NEW:状态是指线程刚创建, 尚未启动。
  • RUNNABLE:状态是线程正在正常运行中, 当然可能会有某种耗时计算/IO等待的操作/CPU时间片切换等, 这个状态下发生的等待一般是其他系统资源, 而不是锁, Sleep等
  • BLOCKED:这个状态下, 是在多个线程有同步操作的场景, 比如正在等待另一个线程的synchronized 块的执行释放, 或者可重入的 synchronized块里别人调用wait() 方法, 也就是这里是线程在等待进入临界区
  • WAITING:这个状态下是指线程拥有了某个锁之后, 调用了他的wait方法, 等待其他线程/锁拥有者调用 notify / notifyAll 一般该线程可以继续下一步操作
  • TIMED_WAITING: 这个状态就是有限的(时间限制)的WAITING, 一般出现在调用wait(long), join(long)等情况下, 另外一个线程sleep后, 也会进入TIMED_WAITING状态
  • TERMINATED:这个状态下表示 该线程的run方法已经执行完毕了, 基本上就等于死亡了(当时如果线程被持久持有, 可能不会被回收)

  要区分 BLOCKED 和 WATING 的区别, 一个是在临界点外面等待进入, 一个是在理解点里面wait等待别人notify, 线程调用了join方法 join了另外的线程的时候, 也会进入WAITING状态, 等待被他join的线程执行结束。核心区别就是BLOCKED没拿到锁,WAITING拿到了锁。

  4、线程优先级Priority

  线程的优先级是将该线程的重要性传给了调度器、cpu处理线程顺序有一定的不确定,但是调度器会倾向于优先权高的先执行。

  5、线程实现方式

  线程有三种实现方式:Thread、Runnable、Callable。

  Thread实现方式代码如下:

public class Thread01 extends Thread {

   @Override
   public void run() {
      System.out.println("Thread 方式创建线程");
   }

   public static void main(String[] args) throws InterruptedException {
      new Thread01().start();//多线程
   }
}

  Runnable实现方式:

public class Runnable01 implements  Runnable {
   @Override
   public void run() {
      System.out.println("Runnable方式创建线程");
   }

   public static void main(String[] args) {
      new Thread(new Runnable01()).start();
   }
}

  Callable实现方式:

public class Callable01 implements Callable<String> {
   @Override
   public String call() throws Exception {
      System.out.println("Callable方式创建线程");
      return "Callable";
   }

   public static void main(String[] args) throws ExecutionException, InterruptedException {
      FutureTask task=new FutureTask(new Callable01());//有参 赋值 成员属性
      new Thread(task).start();
      System.out.println( task.get());;
   }
}

  6、Thread和Runnable的联系与区别

  • Runnable的实现方式是实现其接口即可。
  • Thread的实现方式是继承其类。
  • Runnable接口支持多继承,但基本上用不到。
  • Thread实现了Runnable接口并进行了扩展,而Thread和Runnable的实质是实现的关系,不是同类东西,所以Runnable或Thread本身没有可比性。public class Thread implements Runnable { // 省略 @Override public void run() { if (target != null) { target.run(); } } // 省略 }

  综上所述:Thread和Runnable的实质是继承关系,没有可比性。无论使用Runnable还是Thread,都会new Thread,然后执行run方法。用法上,如果有复杂的线程操作需求,那就选择继承Thread,如果只是简单的执行一个任务,那就实现runnable。

  7、Callable原理是什么

  Callable 1.5引入,具有返回值,并且支持泛型:

public interface Callable<V> {
    V call() throws Exception;
}

  返回加入泛型既可以返回Object,也可以让调用限定类型,更灵活。Callble相关源码如下:

public interfa
深入学习C++底层 文章目录C++内存管理LINUX进程区分段及存储数据GCC编译流程动态库静态库区别及GCC加载库extern-C的结果和CPP编译的区别重载的底层原理编译性语言和解释性语言的本质区别和优缺点 C++内存管理 栈 存储函数的返回地址、参数、局部变量、返回值,从高地址向低地址增长 堆 malloc/free开辟内存的空间,从低地址向高地址增长 自由存储区 new/delete开辟内存空间 数据区 数据区包含全局/静态存储区和常量存储区,存储已初始化的全局变量和静态变量、未初始化的全局变量和静态变量及字符串常 阅读详情

相关推荐

深入浅出:使用MDC构建SpringBoot全链路请求追踪系统(实战避坑版)

做微服务开发的,大概率都有过这样的崩溃时刻:用户反馈“下单接口偶尔失败,但重试又能成功”,你去查日志,发现网关日志、订单服务日志、支付服务日志、库存服务日志、异步通知日志杂乱无章,没有任何统一标识——你分不清哪条日志属于同一个请求,只能凭着时间戳、用户ID一点点筛选,翻了几十分钟甚至几小时,才勉强串联起链路,定位到问题根源。这就是微服务开发中“日志碎片化”的痛点,尤其是在高并发场景下,一个请求可能经过网关、多个微服务、多个异步线程,没有统一的追踪标识,排查问题的效率极低。

2601_94871597的博客 737

深入解析C++编程中线程池的使用

为什么需要线程池 目前的大多数网络服务器,包括Web服务器、Email服务器以及数据库服务器等都具有一个共同点,就是单位时间内必须处理数目巨大的连接请求,但处理时间却相对较短。 传 统多线程方案中我们采用的服务器模型则是一旦接受到请求之后,即创建一个新的线程,由该线程执行任务。任务执行完毕后,线程退出,这就是是“即时创建,即 时销毁”的策略。尽管与创建进程相比,创建线程的时间已经大大的缩短,但是如果提交给线程的任务是执行时间较短,而且执行次数极其频繁,那么服务器将处于 不停的创建线程,销毁线程的状态。 我们将传统方案中的线程执行过程分为三个过程:T1、T2、T3。 T1:线程创建时间

WSL 相关命令时遇到了 “无法从raw.githubusercontent.com提取分发列表、操作超时

核心问题:国内网络屏蔽raw.githubusercontent.com,导致WSL无法获取发行版列表;最优方案:优先用方案1(手动指定发行版安装),无需改配置,1分钟搞定;永久修复:用方案2(修改hosts),适合需要管理多个WSL发行版的场景;兜底方案:用方案3(手动下载安装包),适配所有网络环境。按以上步骤操作后,你不仅能正常安装WSL,等命令也能正常执行,后续可正常使用WSL搭配Docker Desktop(如切换WSL 2后端),无需再担心网络超时问题。

weixin_39766667的博客 2220

机器学习kaggle案例:风控评分卡模型(Give_Me_Some_Credit)

kaggle链接:https://www.kaggle.com/c/GiveMeSomeCredit ipynb文件:https://github.com/824024445/KaggleCases/blob/master/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0kaggle%E6%A1%88%E4%BE%8B%EF%BC%9A%E9%A3%8E%E6%8E%A7%...

weixin_42662126的博客 1万+

别再到处找模型了!手把手教你将TI、ADI官网的SPICE模型导入LTspice(附路径避坑指南)

本文详细介绍了如何将TI、ADI官网的SPICE模型导入LTspice的全流程,包括模型获取、路径配置、符号生成等关键步骤,并提供了路径避坑指南。通过实战案例和技巧分享,帮助电子工程师高效利用外部元器件模型进行电路仿真,提升设计效率。

weixin_42535703的博客 422

ArcGIS Pro MCP 开源:自然语言驱动的 AI 制图与分析

人工智能与大模型的快速发展,正推动专业软件从“手动操作”走向“自然语言控制”。模型上下文协议(MCP)作为连接 AI 与外部工具的标准接口,类似为 AI 安装的“USB 接口”,让大模型可以通过统一协议调用 GIS 软件能力。基于 ArcPy 构建的 ArcGIS Pro MCP 项目,将复杂的地图制图与空间分析封装为 112 个可被 AI 调用的工具,使文本指令直接驱动软件完成数据加载、符号化、出图乃至叠加统计等任务。对 GIS 工程师、数据分析师与测绘规划从业者而言,该开源项目显著降低专业软件使用门槛,

weixin_29054195的博客 289

Cadence IC618版图DRC验证License报错排查:从虚拟机网络配置到HOSTID的实战解析

本文详细解析了Cadence IC618版图设计中DRC验证License报错的排查方法,重点从虚拟机网络配置到HOSTID获取的实战经验。通过对比ifconfig与ip add命令的差异,提供了正确的HOSTID获取方式及License文件修改技巧,帮助工程师快速解决IC618环境下的DRC验证问题。

weixin_30823001的博客 686

RK3576 调试ov2735 mipi-csi摄像头

摘要:本文记录了基于RK3576平台调试OV2735 MIPI摄像头的全过程。开发环境采用Linux 6.1内核和Buildroot文件系统。调试步骤包括:1)硬件检查(电源、晶振和引脚连接);2)驱动配置(设备树节点、ISP通道设置);3)驱动验证(通过ID检测和I2C工具测试);4)推流测试(使用v4l2和gstreamer工具)。重点解决了复位引脚配置、时钟命名匹配等关键问题,并通过寄存器检查确保初始化正常。最终实现了摄像头数据流的成功输出,为嵌入式视觉应用开发提供了完整参考方案。

qq_45147279的博客 1073

利用 AI 自动生成 BDD(行为驱动开发)格式的 Gherkin 测试用例

文章摘要 当前BDD测试领域正经历AI驱动的变革浪潮。传统Gherkin用例编写面临四大痛点:语法负担重、场景发现成本高、一致性差和维护困难。2025-2026年,AI生成Gherkin的工具生态快速成熟,主要分为五类:测试管理平台内置AI(如TestRail 10.2)、Jira插件(如AssertThat BDD)、独立AI平台(如PrimeCompass)、CLI工具和研究原型。其中,TestRail实现生成-执行闭环,AssertThat采用多阶段Agent工作流提升质量,PrimeCompass则

ZXSXJ的博客 211

Oracle EBS 帐套(Ledger/SOB)如何定义会计主体、如何支撑多准则 / 多报告、组织与帐套的绑定关系、以及项目落地时的设计差异。下面从实现逻辑、核心要素、组织模型、多账簿、科目设计、项

本文对比了Oracle EBS R12与SAP S/4HANA在帐套(Ledger)设计上的核心差异。Oracle采用4C架构(科目/币种/日历/准则),帐套作为独立会计主体,主辅账物理隔离;SAP则以公司代码为主体,通过平行分类账在同一凭证中实现多准则核算。关键差异体现在:Oracle强调边界隔离,适合差异大的集团;SAP注重统一视图,适合实时合并需求。实施时需注意:Oracle避免过度建账套,SAP需统筹科目与维度设计。两者分别体现了"盒子"与"滤镜"的设计哲学。

金牌架构师 427

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

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

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

上一篇: linux网络编程—7层网络以及5种Linux IO模型以及相应IO基础
下一篇: Redis学习之Redis概述及原理、基本操作及持久化
Linux服务器开发
博客等级 码龄7年 610粉丝 589原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址