当前位置:网站首页>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
边栏推荐
- 网络安全-浅谈安全威胁
- Qtablewidget lazy load remaining memory, no card!
- Steps to obtain SSL certificate private key private key file
- [fh-gfsk] fh-gfsk signal analysis and blind demodulation research
- Do not log in or log in to solve the problem that the Oracle database account is locked.
- word插入公式/endnote
- [day 29] given an integer, please find its factor number
- C#应用程序界面开发基础——窗体控制(2)——MDI窗体
- Everything文件搜索工具
- 网络安全-木马
猜你喜欢

【數據挖掘】任務6:DBSCAN聚類

Tâche 6: regroupement DBSCAN
![[data mining] task 6: DBSCAN clustering](/img/af/ad7aa523b09884eee967c6773a613f.png)
[data mining] task 6: DBSCAN clustering
![[principles of multithreading and high concurrency: 2. Solutions to cache consistency]](/img/ce/5c41550ed649ee7cada17b0160f739.jpg)
[principles of multithreading and high concurrency: 2. Solutions to cache consistency]

Main features of transport layer TCP and TCP connection

【数据挖掘】任务2:医学数据库MIMIC-III数据处理

Give you an array numbers that may have duplicate element values. It was originally an array arranged in ascending order, and it was rotated once according to the above situation. Please return the sm
![[data mining] task 5: k-means/dbscan clustering: double square](/img/e7/678197e703d1a28b765a0e3afd5580.png)
[data mining] task 5: k-means/dbscan clustering: double square
![[shutter] animation animation (basic process of shutter animation | create animation controller | create animation | set value listener | set state listener | use animation values in layout | animatio](/img/70/54eb9359ac91aa43383b240eb036b7.gif)
[shutter] animation animation (basic process of shutter animation | create animation controller | create animation | set value listener | set state listener | use animation values in layout | animatio
![[understanding of opportunity -36]: Guiguzi - flying clamp chapter - prevention against killing and bait](/img/c6/9aee30cb935b203c7c62b12c822085.jpg)
[understanding of opportunity -36]: Guiguzi - flying clamp chapter - prevention against killing and bait
随机推荐
Button wizard play strange learning - automatic return to the city route judgment
Steps to obtain SSL certificate private key private key file
A simple tool for analyzing fgui dependencies
Mathematical knowledge: step Nim game game game theory
[QT] encapsulation of custom controls
Leetcode skimming questions_ Sum of two numbers II - enter an ordered array
Test shift right: Elk practice of online quality monitoring
[data mining] task 4:20newsgroups clustering
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research
【数据挖掘】任务3:决策树分类
Vim 9.0正式发布!新版脚本执行速度最高提升100倍
Wireshark data analysis and forensics a.pacapng
【数据挖掘】任务4:20Newsgroups聚类
Is there anything in common between spot gold and spot silver
[shutter] animation animation (animatedbuilder animation use process | create animation controller | create animation | create components for animation | associate animation with components | animatio
C#应用程序界面开发基础——窗体控制(4)——选择类控件
QTableWidget懒加载剩内存,不卡!
网络安全-最简单的病毒
给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】
[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