当前位置:网站首页>Introduction to kotlin collaboration
Introduction to kotlin collaboration
2022-07-03 01:40:00 【AnRFDev】
development environment
- IntelliJ IDEA 2021.2.2 (Community Edition)
- Kotlin: 212-1.5.10-release-IJ5284.40
Introduce Kotlin Association in . Use an example to show the basic usage of coprocessing .
First example
New project
We use the community version IntelliJ IDEA 2021.2.2. Create a new one Kotlin Engineering is used to test .
Lead in process
The project with gradle Conduct management , We are Github Find the dependency of the synergy on .
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}
- 1.
- 2.
- 3.
Project modification gradle To configure . Add dependencies .
Code example
Create a class and then main
Method to write the relevant code of the coroutine .
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main() {
GlobalScope.launch { // Start a new process in the background and continue
delay(300) // wait for 300 millisecond
"rustfisher.com".forEach {
print(it)
delay(200) // Wait every time you print
}
}
println("RustFisher")
Thread.sleep(3000) // Blocking the main thread prevents too fast exit
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
Code run results
Essentially , A coroutine is a lightweight thread .
We use it GlobalScope Started a new collaborative process , This means that the life cycle of the new collaboration is limited only by the life cycle of the entire application .
Can be GlobalScope.launch { …… }
Replace with thread { …… }
, And will delay(……)
Replace with Thread.sleep(……)
Achieve the same purpose . Pay attention to the import package kotlin.concurrent.thread
Replace a coroutine with a thread
import java.lang.Thread.sleep
import kotlin.concurrent.thread
fun main() {
thread {
sleep(300)
"rustfisher.com".forEach {
print(it)
sleep(200)
}
}
println("RustFisher")
sleep(3000) // Blocking the main thread prevents too fast exit
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
If thread{}
contains delay
, The compiler will report an error
Suspend function 'delay' should be called only from a coroutine or another suspend function
because delay
It's a special one Suspend function , It doesn't block threads , But will Hang up coroutines , And it can only be used in the cooperation process .
thus , To summarize the first collaborative process example
- gradle Lead in process
kotlinx-coroutines-core
-
GlobalScope.launch
Start the coroutines - In the process of cooperation Hang up function
delay(long)
It can achieve the effect of delay , And it can only be used in collaboration
The thread where the coroutine is located
Essentially, a coroutine is a lightweight thread . Let's look at the thread information where the coroutine is located .
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.Thread.sleep
fun main() {
println("main Thread information ${Thread.currentThread().id}")
for (i in 1..3) { // Start the process several times
GlobalScope.launch {
println(" Start the process #$i Thread id: ${Thread.currentThread().id}")
}
}
sleep(2000) // Blocking the main thread prevents too fast exit
println("RustFisher The example ends ")
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
function log as follows
main Thread information 1
Start the process #1 Thread id: 11
Start the process #3 Thread id: 14
Start the process #2 Thread id: 13
RustFisher The example ends
- 1.
- 2.
- 3.
- 4.
- 5.
You can see that the process is started many times , These coroutines are not necessarily in the same thread . In other words, there are Same thread The possibility of .
So try to start the process crazily , Increase the number of cycles for (i in 1..3000)
. Observe log It can be seen that , There are duplicate threads id.
Records of a software engineer
边栏推荐
- STM32 - GPIO input / output mode
- Vim 9.0正式发布!新版脚本执行速度最高提升100倍
- Installation and use of serial port packet capturing / cutting tool
- [Cao gongzatan] after working in goose factory for a year in 2021, some of my insights
- Everything文件搜索工具
- Create your first Kivy program Hello word (tutorial includes source code)
- Soft exam information system project manager_ Real topic over the years_ Wrong question set in the second half of 2019_ Morning comprehensive knowledge question - Senior Information System Project Man
- 云原生题目整理(待更新)
- SSL flood attack of DDoS attack
- Qtablewidget lazy load remaining memory, no card!
猜你喜欢
[机缘参悟-36]:鬼谷子-飞箝篇 - 面对捧杀与诱饵的防范之道
Steps to obtain SSL certificate private key private key file
C application interface development foundation - form control (2) - MDI form
LeetCode 987. Vertical order transverse of a binary tree - Binary Tree Series Question 7
Expérience de recherche d'emploi d'un programmeur difficile
Three core issues of concurrent programming - "deep understanding of high concurrent programming"
leetcode刷题_两数之和 II - 输入有序数组
Summary of interval knowledge
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research
串口抓包/截断工具的安装及使用详解
随机推荐
网络安全-病毒
网络安全-漏洞与木马
Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads
Tp6 fast installation uses mongodb to add, delete, modify and check
[North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array
Scheme and practice of cold and hot separation of massive data
C#应用程序界面开发基础——窗体控制(2)——MDI窗体
Meituan dynamic thread pool practice ideas, open source
Thinkphp+redis realizes simple lottery
[day 29] given an integer, please find its factor number
【面试题】1369- 什么时候不能使用箭头函数?
MySQL - database query - condition query
What are the trading forms of spot gold and what are the profitable advantages?
[principles of multithreading and high concurrency: 2. Solutions to cache consistency]
Take you ten days to easily complete the go micro service series (I)
简易分析fgui依赖关系工具
Kivy tutorial - example of using Matplotlib in Kivy app
Leetcode 2097 - Legal rearrangement of pairs
The thread reuse problem of PageHelper using ThreadLocal, did you use it correctly?
High-Resolution Network (篇一):原理刨析