Search code examples
multithreadingkotlintornadofx

Background thread


So i want to create an thread which is running until i close the Application. But i dont know how to do that probably with TornadoFx

This is what i have and i am getting an IllegalThreadStateException.

override fun start(stage: Stage) {
    super.start(stage)
    thread {
        Thread.sleep(2000)
        println("running")
    }.start()
}

Also it is only executed once and than the thread basically stops but this might be because of the exception.


Solution

  • What your code is doing is starting a thread using the thread builder, and then calling start on that same thread again, hence you get the IllegalThreadStateException.

    The reason for this is that the kotlin thread builder has a start parameter, which by default is true. So you can just remove your .start() call and the thread would start normally. You could also pass start = false to the thread builder and instead call .start() like you did.

    However, the thread code you posted will simply wait for 2 seconds, then print "running" and then exit. A thread is not a loop by default, so after 2 seconds and change, the thread has done what you asked it to.