创建一个demo想测试一下协程程序,引入后提示:
Unresolved reference: kotlinx
代码为
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // 在后台启动一个新的协程并继续
delay(1000L)
println("World!")
}
println("Hello,") // 主线程中的代码会立即执行
runBlocking { // 但是这个表达式阻塞了主线程
delay(2000L) // ……我们延迟 2 秒来保证 JVM 的存活
}
}
原来build.gradle 文件配置
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.10'
}
group '11'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
解决:
在 dependencies 中添加上
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1"
最后我的build.gradle 文件
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.10'
}
group '11'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
// compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
// testCompile group: 'junit', name: 'junit', version: '4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
implementation "org.jetbrains.kotlin:kotlin-reflect"
// 就是这个配置项
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1"
implementation group: 'org.eclipse.paho', name: 'org.eclipse.paho.client.mqttv3', version: '1.1.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation fileTree('libs')
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
注意:需要 import changes 才能生效。