Selvarathinam Vinoch
Selvarathinam Vinoch

Reputation: 1100

How to resume a thread

I'm using three threads in my code.When i press 'stop' button it should stop and 'start' button should resume them..here is my code :

 private void jButton_stopActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    boolean result = value;
    if(result){
        t.stop();
        timer.stop();
        timer2.stop();
        value = false;
        jButton_stop.setText("Start");
    }
    else{
        t.resume();
        timer.resume();
        timer2.resume();
        value = true;
        jButton_stop.setText("Stop");
    }

But when i click the 'stop' button all the threads are stopped perfectly,but when i press 'start' button threads are not resuming .why?? please help me.

Upvotes: 2

Views: 165

Answers (2)

Diego C Nascimento
Diego C Nascimento

Reputation: 2801

Considering t is an instance of Thread:

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

from http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

And, Thread.stop() is deprecated.

The thread itself should check if it needs to finish, like a boolean run variable being checked, or using objects for thread communication.

Upvotes: 4

Rameez
Rameez

Reputation: 1712

You can keep it on waiting based on some boolean value, for example:

 public void run() {
      try {
      for(int i = 15; i > 0; i--) {
         System.out.println(name + ": " + i);
         Thread.sleep(200);
         synchronized(this) {
            while(suspendFlag) {
               wait();
            }
          }
        }
      } catch (InterruptedException e) {
         System.out.println(name + " interrupted.");
      }
      System.out.println(name + " exiting.");
   }

Here you can change suspendFlag status outside thread. see here

Upvotes: 1

Related Questions