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.
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.