I have two threads, one of them starts when i press a button. it just display values from 1-20 on the button btn.settext(""+ j)
. inside the listener fo that button I wrote the following:
btn_listener.setOnClickLstener(new Listener) {
public void onClickListener(view v) {
if (!t2.isAlive()) {
t2.start()
}
}
}
t2 is a thread. what happens at run time is, when I click the button while the thread2 is running nothing happens, but, when the thread2 finishes it job and i ckick the button the app crashes. any reason why that happens?
A thread cannot be restarted.
According to SCJP by Kathy Sierra:
After you called the
start()
method on a thread, it cannot be restarted; it runs until completion, then it dissolves, and is considered dead (although you can still call its specific methods on it, you cannot call start() again).If you call
start()
a second time, it will cause an exception (anIllegalThreadStateException
, which is aRuntimeException
).