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.

1
  • 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. Commented Sep 10, 2021 at 3:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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).
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?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.