user633784
user633784

Reputation:

is there anyway to run a thread while giving it an argument?

Can anyone tell me if there's a way to run a thread and give it an argument ? its like Giving an argument to that Runnable's run method , sth like

class Test implements Runnable 
{
     public void run( char a ) { // the question's here ,
                                 //is there any way to run a thread , 
                                 //indicating an argument for it ? 
        do  something with char a ;  
     }
}

Upvotes: 1

Views: 470

Answers (3)

Stephen C
Stephen C

Reputation: 718788

The Runnable.run() method does not take any arguments, and you can't change that. But there are ways to pass input to and return output from a Thread. For instance:

public int someMethod(final int arg) throws InterruptedException {
    final int[] result = new int[1];
    Thread t = new Thread(new Runnable() {
        public void run() {
            result[0] = arg * arg;
        }
    });
    t.start();
    // do something else
    t.join();
    return result[0];
}

Note that the run() method can only refer to final variables of the enclosing method, but those variables can be references to mutable objects; e.g. the int[].

A variation of this is to use instance variables of the enclosing Class.

Alternatively, you can create a subclass of Thread, implement its run() method, and use constructor arguments, getters and/or setters to pass arguments and results.

Upvotes: 0

theomega
theomega

Reputation: 32031

No, thats not possible, simply due to the fact, that the Runnable interface has no argument for the run method. You could assign the value to a member-variable of the Thread and use it:

class Test implements Runnable 
{
     private final char a;

     public Test(char a) {
         this.a  = a;
     }

     public void run() {
       // do  something with char a ;  
     }
}

Upvotes: 4

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

You can say, Yes and No.

NO : run() method defined in the Runnable interface takes no argument. Since you implement the Runnable interface, you will be implementing the run() method of Runnable interface, which happens to be a no-arg method.

YES : You can however, create overloaded method of run(), which can take argument. Compiler will not complain about it. But remember one thing, this will never be called when the thread is started. It will always call the no-arg run() method.

e.g

class Test implements Runnable 
{
     public void run() {
      // ... thread's task, when it is started using .start()
      }

     // Overloaded method  : Needs to be called explicitly.
     public void run(char a) { 
      //do  something with char a ;  
     }
}

Upvotes: 3

Related Questions