将Java线程转换为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() 

PS我已经阅读了这篇文章,但我不知道如何适应它。

您可以转换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() }