Kotlin之深入理解协程

Kotlin协程详解(学习协程这一篇就够了) 一、什么是协程协程是一种优雅处理异步任务的解决方案 ,可以理解为是Kotlin对「线程」和「Handler」 API 的一种封装形式。它可以在不同的线程间来回切换,这样就可以让代码通过编写的顺序来执行,并且不会阻塞当前线程,省去了在各种耗时操作写回调的情形。在 JVM 平台上,Kotlin 协程是无栈协程,所谓无栈协程,是指协程在 suspend 状态时不需要保存调用栈。 阅读详情

1 协程基础

1.1 带问题理解协程

GlobalScope.launch(Dispatchers.Main) {
   
   
     suspendSimpleDelay()
}

suspend fun suspendSimpleDelay(): Unit {
   
   
     withContext(Dispatchers.IO) {
   
   
          delay(10000) 
     }
}

1.2 Kotlin协程中挂起的是什么?

协程。

1.3 什么是协程?

kotlin协程为launch()、async() 等中的代码,协同多个程序之间进行合作,帮助我们轻松的写出复杂的并发代码。launch在创建的一个协程,在执行到某一个suspend函数(挂起函数)时,这个协程会被 suspend(被挂起)。

1.4 协程是执行在单线程中的吗?

协程本质上还是一套基于原生Java Thread API 的封装。只要没有魔改JVM,start了几个线程,操作系统就会创建几个线程;Kotlin协程只是做了一个类似线程池的封装,根本谈不上什么性能更好。协程是协作式任务,线程是抢占式任务,本质上两者都属于并发。

1.5 什么时候要用到协程的?

需要切换线程的时候要用到协程。

1.5.1 挂起是怎么做到的?

在suspend修饰的挂起函数中,调用另外一个协程自带的、内部实现了协程挂起代码的挂起函数withContext(),让它来做真正的挂起,实现线程切换的工作。

1.5.2 挂起的本质是什么?

挂起的本质是切线程。

1.5.3 既然suspend不能真正的做到挂起函数,那么suspend的作用是什么呢?

(1)作用是:提醒,提醒调用者该函数为耗时操作,避免主线程调用了一个耗时操作。因此创建一个挂起函数,一定要在内部调用别的挂起函数,否则这个挂起函数就是没有必要的。
在这里插入图片描述
(2)withContext的两种写法:

private suspend fun doWord(): Int {
   
     // 写法1
    withContext(Dispatchers.IO) {
   
   
    	delay(5000L)
        LogUtils.d(TAG, "suspendLaunch World! ${Thread.currentThread()}")
    }
    return 1
}

private suspend fun doWord2(): Int = withContext(Dispatchers.IO) {
   
    // 写法2
	delay(5000L)
    LogUtils.d(TAG, "suspend
Kotlin协程详解——协程基础 你通常会看到 runBlocking 在应用程序的最顶层被这样使用,而在真正的代码中却很少见到它的身影,因为线程是宝贵的资源,阻塞它们是低效的,而且通常是不被期望的。协程遵循结构化并发的原则,这意味着新的协程只能在特定的 CoroutineScope 内启动,该作用域限定了协程的生命周期。这些情况导致的问题是代码间的嵌套层级太深,导致逻辑嵌套复杂,后续的维护成本也要提高,这不是我们所要看到的。协程可以被视为轻量级的线程,但它们之间存在一些重要的区别,这使得它们在实际使用中与线程有很大的不同。 阅读详情

相关推荐

Kotlin 协程(Coroutines)详解

Kotlin 协程(Coroutines)详解

HeDongDong的博客 1122

Kotlin 协程1:深入理解withContext

在 Kotlin 中,协程提供了一种优雅和高效的方式来处理异步编程和并发。在这篇文章中,我们将深入探讨 Kotlin 协程中的一个重要函数:withContext。

jiet_h的博客 5307

SAP传输请求实战:从SE09/SE10到STMS的完整操作指南

本文是SAP传输请求的完整实战指南,详细讲解了从开发到生产环境的代码与配置安全流转流程。内容涵盖SE09/SE10创建与释放请求、SCC1客户端内复制以及STMS跨系统传输的核心操作,并提供了常见问题排雷与全流程演练,帮助顾问掌握系统变更可控、可追溯的关键技能。

ik678901的博客 425

6层高速PCB设计实战:BGA布局与阻抗匹配关键解析

本文深入解析6层高速PCB设计中BGA布局与阻抗匹配的关键技术。通过实战经验分享,详细介绍了六层PCB层叠结构的选择与优化、BGA器件布局技巧、阻抗匹配的实战经验以及高速布线技巧,帮助工程师提升PCB设计水平,确保信号完整性和电源完整性。

weixin_28481133的博客 373

智能车竞赛独轮组信标灯系统全解析:从硬件选型到实战调试

本文全面解析了智能车竞赛独轮组信标灯系统的核心原理与实战应用。从硬件架构(灯板、灯罩、控制器)的深度剖析,到红外信号(特别是40kHz调制信号)的接收与解码策略,再到车模的灭灯机构设计与路径规划,提供了从硬件选型到软件调试的全链路指南。文章重点分享了实战调试技巧与常见问题排查方法,旨在帮助参赛队伍深入理解系统,提升车模的识别精度与比赛表现。

e4f5g6h的博客 1135

ISO15118-20证书结构关系解读(7.3.2.1)

本文主要讲述ISO15118-20:2022标准所有证书结构的关联关系,目的是为后续基于ISO15118-20车桩通讯及PNC充电等提供基础支撑。 本文所有的证书关系图全部来源于ISO15118-20:2022标准规范,在后续的讲解过程会将图的摘取出处给提供出来,便于后期文章和标准对应起来解读。

weixin_40900932的博客 3215

Computer Networks 和 Computer & Security投稿经验

论文投稿

qq_50604294的博客 9295

Ubuntu下安装Hive3.1.2教程(附MySQL安装方法及安装包)

文章目录前言一、安装Hive1. 下载压缩包并解压2. 安装Hive3. 配置环境变量4. 修改配置文件二、MySQL安装与配置1. 安装MySQL2. 安装MySQL jdbc包3. 为Hive创建MySQL账号三、验证Hive安装及错误处理1. 启动Hadoop2. 启动hive3. 运行Hive实例总结 前言 Hive 的安装需要建立在 Hadoop 的之上(类似于Hbase),关于 Hadoop 的单机安装以及伪分布式安装可以参考作者的另两篇博客: Ubuntu下单机安装Hadoop详细教程(附

程序必须为人类阅读而编写,并且仅仅碰巧可以让机器执行 1万+

Linux下驱动开发_块设备驱动开发(硬件上采用SD卡+SPI协议)

这一篇文章将采用SD卡作为存储硬件,利用SPI协议与SD卡通信,完成块设备驱动开发测试。 SD卡可以更加形象的表示块设备开发过程,明白硬件如何交互,完成数据读写。

2614

文章ACCEPT之后填写内容教程-Springer-Verlag即施普林格

1. 确认corresponding author通讯作者机构是否正确(最好细分到系,如搜不到系只填大学也可)这些信息因为在投稿的时候都填过,所以一般都没问题,可确认并继续。2. Co-Author: 这篇文章有没有其他作者,如果有就选yes,并确认投稿时所填的作者姓名和机构是否正确。这个也是如果前期都填对了就不用修改。3. Research funders: 问文章的研究有没有资助,没有就选no,有就选yes,并填写机构名称和grant/contact numbers。

ZhangJiqun&191cm&85kg 4835

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

Statistics and Machine Learning Toolbox

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

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

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

上一篇: Kotlin之精选
下一篇: Android系统分析之带着问题看Handler
一枚-狗子
博客等级 码龄14年 1619粉丝 192原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值