从 Java 调用时,Kotlin 挂起函数在延迟后不执行

Kotlin suspend function not executing after delay when called from Java

我正在尝试从我的 Java class 调用此 Kotlin 暂停代码。该解决方案基于此处提到的内容。

Kotlin 代码:

Main.kt

suspend fun doWorld() = coroutineScope {
    launch {
        println("Thread name2 ${Thread.currentThread().name}")
        delay(2000L)
        println("Hello world")
    }
}
@OptIn(DelicateCoroutinesApi::class)
fun doSomethingAsync() =
    GlobalScope.future { doWorld() }

Converter.java

public class Converter {
    public static void main(String[] args) {
       MainKt.doSomethingAsync();
    }
}

当我从 Java class 调用 doSomethingAsync() 时,我没有看到任何打印语句。有人可以解释一下到底发生了什么以及我该如何纠正这个问题。

我认为在您的情况下,程序会在新协程启动之前完成。调用MainKt.doSomethingAsync()后尝试在main函数中延迟当前Main Thread:

public class Converter {
    public static void main(String[] args) {
       MainKt.doSomethingAsync();
       try {
            TimeUnit.MILLISECONDS.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Or use MainKt.doSomethingAsync().get()
    }
}

那我估计会显示日志。