当前位置:网站首页>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
边栏推荐
- [C language] detailed explanation of pointer and array written test questions
- [FPGA tutorial case 5] ROM design and Implementation Based on vivado core
- 简易分析fgui依赖关系工具
- [day 29] given an integer, please find its factor number
- 网络安全-扫描与密码爆破2
- Expérience de recherche d'emploi d'un programmeur difficile
- uniapp组件-uni-notice-bar通告栏
- 网络安全-病毒
- PS去除水印详解
- STM32 - switch of relay control lamp
猜你喜欢

Wireshark data analysis and forensics a.pacapng

Pytest learning notes (12) -allure feature · @allure Step () and allure attach

给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】

Using tensorboard to visualize the model, data and training process

Introduction to flask tutorial

【数据挖掘】任务3:决策树分类

【面试题】1369- 什么时候不能使用箭头函数?
![[fh-gfsk] fh-gfsk signal analysis and blind demodulation research](/img/8a/8ca80f51a03341c982d52980c54b01.png)
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research

音程的知识的总结

Arduino dy-sv17f automatic voice broadcast
随机推荐
What are the trading forms of spot gold and what are the profitable advantages?
【面试题】1369- 什么时候不能使用箭头函数?
Do not log in or log in to solve the problem that the Oracle database account is locked.
Tp6 fast installation uses mongodb to add, delete, modify and check
[QT] encapsulation of custom controls
网络安全-密码破解
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-9
[FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
[data mining] task 2: mimic-iii data processing of medical database
并发编程的三大核心问题 -《深入理解高并发编程》
Look at how clothing enterprises take advantage of the epidemic
Meituan dynamic thread pool practice ideas, open source
Tâche 6: regroupement DBSCAN
GDB 在嵌入式中的相关概念
Smart management of Green Cities: Digital twin underground integrated pipe gallery platform
Installation and use of serial port packet capturing / cutting tool
Qtablewidget lazy load remaining memory, no card!
电信客户流失预测挑战赛
STM32 - GPIO input / output mode
The thread reuse problem of PageHelper using ThreadLocal, did you use it correctly?