Kyoshiro
Kyoshiro

Reputation: 27

Do I need to use threading?

I need to fix some problem here. I am using java android eclipse.

Problem: If I click add or minus button it will execute those 2 methods, right? What I want is:

  1. If I click button at the same time it should only execute 1 method.
  2. I don't want the add method will be executed simultaneously if i keep pressing the button.
  3. I want to terminate the minus function if ever the add functions is still processing.
  4. How to do this?

Question: Do i need to use threading?

public void Add(int a, int b){
     return a + b;
}

public void Minus(int a, int b){
    return a - b;
}

public void btn_add(View view){
      Add(a,b);
}

public void btn_minus(View view){
      Minus(a,b);
}

Upvotes: 0

Views: 54

Answers (2)

Tenfour04
Tenfour04

Reputation: 93834

Greg Ennis's answer assumes you're concerned because your actual methods are time-consuming, unlike your add and subtract example.

If that is not your concern, I should point out that if these are short-running methods, then you don't need to worry about threading at all. Don't specify any Threads, Runnables, or AsyncTasks. When a button is clicked, it's onClick method will automatically be called on the UI thread, so it will be impossible for any other button clicks to occur until the onClick method (and therefore your add method) returns.

Regarding your point number 1, I don't think Android permits simultaneous button presses.

Upvotes: 0

Greg Ennis
Greg Ennis

Reputation: 15379

I'm assuming you've simplified the tasks you want to perform into methods named add and minus but these are actually more complex tasks that take a non-trivial amount of time. (Otherwise, you wouldn't be worried about clicking again while they are processing).

So, I think you should use threading, but not to take on the complexities of creating and managing worker thread yourself. You should use AsyncTask.

So, the pattern would like:

public void clickAdd(View view) {
  if (mTask.getStatus() != AsyncTask.Status.FINISHED) {
    return;
  }

  mTask.execute(...);
}

private AddTask mTask = new AddTask();

private class AddTask extends AsyncTask {
    public void doInBackground(...) {

    }
}

Upvotes: 1

Related Questions