1

I wonder if it's possible define function that will be called in Thread's run. It can be done by using if statement but is there a better way to do so?

a possible solution

public class WorkerThread extends Thread {
    private String functionToCall = null;

    public WorkerThread(String functionToCall) {
        this.functionToCall = functionToCall;
    }

    public void run() {
        if (functionToCall.equals("func1"))
            func1();
        else if (functionToCall.equals("func2"))
            func2();
    }

    private void func1() {
    }

    private void func2() {
    }

}
Ismail Sahin
  • 2,640
  • 5
  • 31
  • 58
  • 1
    You could use reflection to do this: http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – Thomas Nov 30 '13 at 21:03
  • Why don't you just implement two different `Thread` instances? – phlogratos Nov 30 '13 at 21:03
  • may be for writing less code? – Ismail Sahin Nov 30 '13 at 21:04
  • fane89 maybe you would want to post your comment as an answer – Ismail Sahin Nov 30 '13 at 21:06
  • One class should only solve one problem. If you have two problems you should not mix them up. This principle is called [Separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns). – phlogratos Nov 30 '13 at 21:08
  • yes you are right and I'm already trying to Create a class which has different functions in it that provides different type of data using webservice. So I want my data provider to be only one class. By the way link is broken – Ismail Sahin Nov 30 '13 at 21:10

3 Answers3

5

Yes, pass in a different Runnable object to the constructor, depending on what you want to run. Like this:

new Thread(myRunnable1);

or

new Thread(myRunnable2);

Then you don't need the WorkerThread class.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • @ismail, I would actually go with this answer. Mine is an answer to the your exact question, but this is a much better technique. I would recommend avoiding reflection if possible. – Mad Physicist Nov 30 '13 at 21:26
2

Java reflection provides a way of calling a method by name. The tutorial is available here: http://docs.oracle.com/javase/tutorial/reflect/.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

It is correct but I recommend do this using interfaces.

Dariusz Mazur
  • 587
  • 5
  • 21