简体   繁体   中英

How to use lambda to initialize ThreadFactory with named Thread

With method reference, I could create a ThreadFactory instance with following code:

ThreadFactory factory = Thread::new;

From ThreadFactory's interface definition, Thread::new will be interpreted as constructor with signature public Thread(Runnable target)

Thread also has another overloaded constructor public Thread(Runnable target, String name) ,

I would ask how to use this constructor and method reference/lambda to construct ThreadFactory?

ThreadFactory has a single abstract method, Thread newThread(Runnable) , so we need a lambda that takes a single Runnable and returns a thread. You want to use a method (constructor) that takes two parameters and turn it into a method that only needs one of those parameters.

Creating a function that "reduces" the number of inputs is called currying , and using it is partial application . In this case, you want to partially apply your thread name ahead of time. With a lambda, you can do this:

String name = "thread-name";
ThreadFactory factory = runnable -> new Thread(runnable, name);
// -> captures the value in "name"

Note that this will produce the exact same thread name every time it's called, so you don't want to use this in a case where it will be used repeatedly.

Some libraries, such as Vavr , have built-in support for taking a function with N parameters and fixing one, but it isn't built into the JDK, and fixing a non-first parameter usually requires a custom lambda anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM