Tazmanian Tad
Tazmanian Tad

Reputation: 313

Call class.method in new thread that requires a parameter

Okay so right now I have essentially this code:

class a {

public void ab() {
    b thread = new b();
     thread.bb(this);
    }
}

class b {

    public void bb(a _a) {
     //execute code here in new thread so ab can continue running
    }
}

However this doesn't open it in a new thread, and yes I did research this, all the solutions I found didn't leave any option to send a parameter (this) to the bb method

How to call class.method in new thread that requires a parameter?

Upvotes: 0

Views: 549

Answers (2)

Aubin
Aubin

Reputation: 14883

The question is "How to call class.method in new thread that requires a parameter?"

The answer is "You can't"... but, it's a workaround: use an instance with a constructor to define a "context" of execution.

class MyThread extends Thread {
   MyThread( A a ){
      this.a = a;
   }
   @Override public void run() {
      ... use this.a; // a was the "parameter"
   }
   private A a;
}

MyThread myThread = new MyThread( aValue );
myThread.start();

Upvotes: 2

FThompson
FThompson

Reputation: 28707

To start a thread, you must have an instance of java.lang.Thread, of which b is not. You can extend thread to achieve this.

class b extends Thread {

A Thread runs asynchronously whatever you place in its run() method, which you can override from its original (empty) implementation.

class b extends Thread {

    @Override
    public void run() {
    }
}

However, this doesn't allow you to pass an instance of a. Your best option here is to take an instance of a as an instance variable in the constructor of b.

class b extends Thread {

    private final a _a;

    public b(a _a) {
        this._a = _a;
    }

    @Override
    public void run() {
        //now you can use _a here
    }
}

Finally, to run the thread asynchronously, you don't call the newly implemented run() method, but you call Thread#start(), which invokes the run() method in a new thread.

class a {

    public void ab() {
        b thread = new b(this);
        thread.start();
    }
}

As a side note, standard Java convention is to start class names with capital letters, so you should rename a to A and so forth. This however won't make any difference as far as compilation or execution goes.

Upvotes: 1

Related Questions