Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MainActivity : AppCompatActivity() {
var mWorker: Thread? = null
var running = AtomicBoolean(false)
var counter:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.start).setOnClickListener {
runWorker()
}
findViewById<Button>(R.id.stop).setOnClickListener {
interruptWorker()
}
}
fun runWorker() {
running.set(true)
mWorker = Thread {
while (running.get()) {
try {
Thread.sleep(1000)
counter++
println("counter $counter")
} catch (ex: InterruptedException) {
Thread.currentThread().interrupt()
println("Thread was interrupted, Failed to complete operation")
}
}
}
mWorker?.start()
}
fun interruptWorker() {
running.set(false)
mWorker?.interrupt()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.