0

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?

sam
  • 2,780
  • 1
  • 17
  • 30
rmaik
  • 1,076
  • 3
  • 15
  • 48
  • 3
    You can't restart a thread. – j4rey Nov 29 '14 at 12:54
  • do u mean once a thread did its runnable job it will be dead, or something like that. sorry for the lack of understanding – rmaik Nov 29 '14 at 13:00
  • Yes, you can't restart a thread but you can stop thread and start another one(the same like first one) – simopopov Nov 29 '14 at 13:00
  • From JavaDoc:It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. – pomkine Nov 29 '14 at 13:02
  • yeah once its run method finishes, you can't restart it. You can however reinitialize the thread then start it. So just reinitialize the thread then start it.Problem fix. – j4rey Nov 29 '14 at 13:02
  • http://www.tutorialspoint.com/java/java_multithreading.htm – User Nov 29 '14 at 13:04
  • @j4rey89 well, "reinitializing" a thread is creating a new instance. – User Nov 29 '14 at 13:07
  • @j4rey89 just making it clear for other readers, because the wording may be confusing. – User Nov 29 '14 at 13:22

1 Answers1

3

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 (an IllegalThreadStateException, which is a RuntimeException).

Ram Ghadiyaram
  • 28,239
  • 13
  • 95
  • 121
SummerCode
  • 1,403
  • 1
  • 14
  • 28