[英]How to use lambda to initialize ThreadFactory with named Thread
With method reference, I could create a ThreadFactory instance with following code: 使用方法参考,我可以使用以下代码创建ThreadFactory实例:
ThreadFactory factory = Thread::new;
From ThreadFactory's interface definition, Thread::new
will be interpreted as constructor with signature public Thread(Runnable target)
从ThreadFactory的接口定义中,
Thread::new
将被解释为具有签名public Thread(Runnable target)
构造函数。
Thread also has another overloaded constructor public Thread(Runnable target, String name)
, 线程还有另一个重载的构造函数
public Thread(Runnable target, String name)
,
I would ask how to use this constructor and method reference/lambda to construct ThreadFactory? 我会问如何使用此构造函数和方法reference / lambda构造ThreadFactory?
ThreadFactory
has a single abstract method, Thread newThread(Runnable)
, so we need a lambda that takes a single Runnable
and returns a thread. ThreadFactory
有一个抽象方法Thread newThread(Runnable)
,因此我们需要一个lambda,它需要一个Runnable
并返回一个线程。 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 . 创建一个“减少”输入数量的函数称为currying ,使用它是部分应用程序 。 In this case, you want to partially apply your thread name ahead of time.
在这种情况下,您希望提前部分应用线程名称。 With a lambda, you can do this:
使用lambda,您可以执行以下操作:
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. 一些库( 例如Vavr )内置了对带有N个参数的函数进行固定并对其进行修复的支持,但JDK并未内置该函数,并且对非第一个参数的修复通常无论如何都需要自定义lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.