1

I've seen a lot of questions on threads and impelementing them using interface, but there doesn't seem to be a lot of updated information on how to do it with a lambda expression. I'm kind of new to this so I'm not sure. The typical one looks like:

Thread myThread = new Thread(() -> {
    // Code to be executed inside the thread    
});

If I already have a method already defined and imported, can I do this?

Thread myThread = new Thread(() -> myMethod(a, b)); //where a and b are parameters

Basically I just want to run a method in a thread created and that method also requires some parameters to be passed inside it. How do I achieve this? Trying the above with myMethod gives me a threadCPUTime of -1 (Using MXBean) so I am wondering if I am doing it incorrectly. Any help is appreciated.

Ymi
  • 609
  • 6
  • 18
  • 2
    A thread needs to be started by calling the `start()` method on it. It will not take any cpu time until you start it. – Erwin Bolwidt Sep 10 '21 at 03:39

1 Answers1

2

Your lambda can read final variables in the scope where it is defined. So the easiest thing would be to make final variables for the things you want to pass into myMethod.

final int a = 1;
final int b = 2;
Thread myThread = new Thread(() -> { myMethod(a,b); });
myThread.start();  // don’t forget to execute it, just creating it won’t run the thread 

Actually the variables can be “effectively final”, not technically final. Make a variable and don’t change what’s in it, there isn’t a way for the lambda to detect changes in the variables. But it may be just as well to enforce it with final.

Otherwise don’t use a lambda, define a Runnable or Callable and pass in what it needs through the constructor.

It seems likely to me the real issue is not starting the thread as pointed out in the comments.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • 2
    Note that the variables don't in fact have to be final, just _effectively final_ (which was defined specifically for the purpose of lambda capture). – chrylis -cautiouslyoptimistic- Sep 10 '21 at 03:31
  • I'm still having the same issue (I did start the thread). Could this be because my method also takes in an Object, and the method changes things inside the object? So some variables and datastructures inside the object are being modified. Is this not allowed with a lambda? – Ymi Sep 10 '21 at 03:48
  • @Yui: yeah hard to tell exactly without code. But it would be better to make a Callable and pass the result back in a Future. It’s better to use thread pools instead of creating threads anyway. And the Future would eliminate any visibility issues. This is sounding involved enough that using a lambda may not be the best choice. – Nathan Hughes Sep 10 '21 at 03:56