我有此代码:
new Thread(() -> {
//do things
}).start();
new Thread(() -> {
//do same things
}).start();
我知道我可以声明一个包含lambda的函数:
Function<Integer, Integer> add = x -> x + 1;
我想使此功能保持Runnable
中new Thread
的实现。
但是我不知道在<>
的Function
之间插入什么。
您不需要Function
即可表示可运行任务。实际上,java.util.Function
不能表示Runnable
,因为它不接受任何输入值,也不返回任何内容。假设Runnable
是一个抽象方法接口(它只有run方法),则只能使用lambda表达式实现它。这是它的外观。
Runnable task = () -> System.out.println("My task");
您可以在程序中将此Runnable
实例用作普通的Runnable
命令。这是一个示例用法。
Thread t = new Thread(task);
t.start();