将 Java 个线程转换为 Kotlin

Convert Java Thread to Kotlin

我尝试通过阅读本书“Android 游戏编程来学习 Kotlin by Example”。现在我无法进一步创建线程。在Java中,一个线程首先定义为零,然后用睡眠()延迟。由于我还是新手,我不能根据我的需要自定义代码。这就是我在 Kotlin 中找到线程解释的方式。但我无法将其付诸实践。有人可以告诉我如何使用我的示例执行此操作吗? 我删除了线程的代码行。

public class TDView extends SurfaceView implements Runnable {

//Thread related
volatile boolean playing;
Thread gameThread = null; //Line 29
...
private void control() {
    try {
        gameThread.sleep(17);          //Line 310
    } catch (InterruptedException e) {
        //catch things here
    }
}

public void pause() {
    playing = false;
    try {
        gameThread.join();             //Line 319
    } catch (InterruptedException e) {
        //catch things here
    }
}

public void resume() {
    playing = true;
    gameThread = new Thread(this);  //Line 327
    gameThread.start();
}

可以找到完整代码here

我想我会这样做:

private val gameThread: Thread? = null
.
//Line 310 same as Java -- here I can't find the sleep-method
//Line 319 same as Java
.
gameThread? = Thread(this)
gameThread.start()

P.S。我已阅读 this 文章,但我不知道如何将其放入。

您可以将代码从 Java 转换为 Kotlin

  1. 在主菜单上,指向代码菜单。
  2. 选择将 Java 文件转换为 Kotlin 文件。

.

@Volatile internal var playing: Boolean = false
internal var gameThread: Thread? = null //Line 29

private fun control() {
    try {

        //because that don't exist you can try that
        //gameThread!!.sleep(17)          //Line 310

        Thread.sleep(17)
        gameThread!!.stop()  //Line 310
    } catch (e: InterruptedException) {
        //catch things here
    }

}

fun pause() {
    playing = false
    try {
        gameThread!!.join()             //Line 319
    } catch (e: InterruptedException) {
        //catch things here
    }

}

fun resume() {
    playing = true
    gameThread = Thread(this)  //Line 327
    gameThread!!.start()
}