I try to learn Kotlin by working through the Book "Android Game Programming by Example". Now I can't get any further in creating threads. In Java, a thread is first defined with zero and later delayed with sleep (). Since I'm still a newbe, I can't customize the code to my needs. That's how I found an explanation for threads in Kotlin. But I can't put it into practice. Can someone tell me how to do this using my example? I cut out the code lines for the threads.
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();
}
The whole code can be found here .
I thought I'd do it like this:
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()
PS I have read this article, but I don't know how to fit it in.
You can convert code from Java to 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()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.