[英]Convert Java Thread to Kotlin
我嘗試通過閱讀《示例Android游戲編程》一書來學習Kotlin。 現在,我無法進一步創建線程。 在Java中,線程首先定義為零,然后使用sleep()延遲。 由於我仍然是新手,因此無法根據需要自定義代碼。 這就是我在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();
}
整個代碼可以在這里找到。
我以為我會這樣:
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()
附言:我已經閱讀了這篇文章,但是我不知道如何適應。
您可以將代碼從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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.