1

I want to do some long running task on a button click, if user click again on that button current task forcefully stopped and will do next task ?

  • What kind of task you are using..Thread,AsyncTask... – Meenal Feb 03 '17 at 04:16
  • 1
    am using thread –  Feb 03 '17 at 04:28
  • @BincyBaby I have added a pure java based solution in my answer. Hope it will be helpful. Only thing you need to take care with my solution is you should not update the GUI from thread other than Main gui thread and if you want to do then use Handler instantiated in main gui thread. Hope my solution will be helpful to you. – nits.kk Feb 05 '17 at 07:36

4 Answers4

0

You can not restart a thread once it is stopped.

I would suggest to use Looper/Handler API to put the tasks in the queue and let the handler execute them on separate thread.

I have demo project for looper/handler here with explanation. Have a look if you want to implement it this way.

Another option (as mentioned by @Guna) is, you can crate cached pool of threads and let the executor run the tasks on threads.

mallaudin
  • 4,744
  • 3
  • 36
  • 68
  • i don't want queue task, i just want to stop previous task and start new –  Feb 03 '17 at 04:45
  • explain in the question what exactly you want to achieve. what kind of task you are performing. etc – mallaudin Feb 03 '17 at 04:52
  • am performing decryption and file creation inside thread, and will play that decrypted temp file, if user click next want play next song –  Feb 03 '17 at 07:01
0

You have to keep checking a flag in your run method. This flag can be set to false when you want the thread to cancel. The next time your run method checks for this flag, since its false hence it exits the thread. May be you want to use a ThreadPoolExecutor?

Guna
  • 338
  • 6
  • 17
0

I am posting a pure Java based code which will work in android as well. While working with android Just you need to take care that you do not update GUI from a part of the program which gets executed in a Thread other than Main GUI thread. If You wish to edit the GUI from another thread then you may use Handler instantiated in the main GUI thread.

Define the basic interface for such model

/**
 * 
 * @author nits.kk
 * 
 * This defines the methods for the model.
 *
 */
public interface IResumable {
  /**
   * starts the model
   */
  public void requestStart();
  /**
   * requests the model to pause
   */
  public void requestPause();
  /**
   * requests the model to resume with new parameter
   * @param newParam
   */
  public void resumeWithNewParam(int newParam);
 /**
   * terminate the model
   */
  public void requestStop();
}

Now the concrete implementation

public class ResumableModel implements IResumable {
  private Thread worker;
  private WorkerRunnable work;

  public ResumableModel(int initialValue) {
        work = new WorkerRunnable(initialValue);
        worker = new Thread(work);
  }

  @Override
  public void requestStart() {
        worker.start();
  }

  @Override
  public void requestPause() {
        work.setPauseRequested(true);
  }

  @Override
  public void resumeWithNewParam(int newParam) {
        work.setNewParam(newParam);
  }

  @Override
  public void requestStop() {
        worker.interrupt();
  }

  private static class WorkerRunnable implements Runnable {
        private int param; // we can have the variable of the type depending upon the requirement.
        private final Object lock = new Object();
        private volatile boolean isPauseRequested = false;

        public void run() {
              synchronized (lock) {
                    try {
                          while (!Thread.currentThread().isInterrupted()) {
                                while (isPauseRequested) {
                                      lock.wait();
                                }
                                System.out.println("value of param is" + param);
                          }
                    } catch (InterruptedException e) {
                          e.printStackTrace();
                    }
              }
        }

        public WorkerRunnable(int param) {
              this.param = param;
        }

        private void setPauseRequested(boolean isPauseRequested) {
              this.isPauseRequested = isPauseRequested;
        }

        private void setNewParam(int param) {
              // double locking to prevent the calling thread from being locked
              // (if in running state without pause requested then calling thread
              // will be in indefinite wait state for acquiring the lock.
              if (isPauseRequested) {
                    synchronized (lock) {
                          if (isPauseRequested) {
                                this.param = param;
                                this.isPauseRequested = false;
                                lock.notifyAll();
                          } else {
                                // logger will be used in real application
                                System.out.println("Need to pause first before setting a new param"); 
                          }
                    }
              } else {
                    // logger will be used in real application
                    System.out.println("Need to pause first before setting a new param"); 
              }
        }
  }
}

Now when you wish to start The thread you can do as below

IResumable resumable = new ResumableModel(10);
resumable.requestStart();

When you want to pause the thread you can simply invoke the requestPause() method

resumable.requestPause();

Now when you need to resume the Thread with a new variable value, you can invoke resumeWithNewParam.

resumable.resumeWithNewParam(20);

Now when you feel you do not need the thread and model should terminate then you can invoke resumable.requestStop();

nits.kk
  • 5,204
  • 4
  • 33
  • 55
-1

You can create thread class like this

public class AsyncThread extends Thread{
        @Override
        public void run() {
            super.run();
            //do your task
        }
    }

And check if the thread is still alive

AsyncThread thread = new AsyncThread();
        if(thread.isAlive()){
            thread.interrupt();
           //do other stuff
        }else{
            thread.start();
        }
Ajay Shrestha
  • 2,433
  • 1
  • 21
  • 25