线程停止

Posted by アライさん on 2019年06月21日

通过interrupt()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private  var thread:Thread? = null
override fun onDestroy() {
Log.d("tag","onDestroy")
thread?.interrupt()
super.onDestroy()
}


thread = Thread(Runnable {
try {
for (i in 0..100) {
val msg = weakHandler.obtainMessage()
msg.obj = i
msg.sendToTarget()
Thread.sleep(3000)
}
}catch (e:InterruptedException){
Log.d("tag",e.toString())
}
})
thread?.start()

通过控制循环令线程完成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private var threadInterrupt = false

override fun onDestroy() {
Log.d("tag","onDestroy")
threadInterrupt = true
super.onDestroy()
}

val thread = Thread(Runnable {
for (i in 0..100) {
val msg = weakHandler.obtainMessage()
msg.obj = i
msg.sendToTarget()
Thread.sleep(3000)

if (threadInterrupt){
Log.d("tag","break")
break
}
}
})
thread.start()