java 如何创建一个线程,Java中如何使用方法引用创建一个线程

方法引用是lambda表达式中引用方法而不执行该方法的一种方式。 在lambda表达式的主体部分,如果另一个方法与函数接口兼容,我们可以调用它们。 我们还可以在方法引用中捕获“this”关键字和“super”关键字。

在下面的两个示例中,我们可以使用方法引用借助“ this ”和“ super ”关键字创建一个线程。

this关键字的示例public class MethodRefThisTest {

public void runBody() {

for(int i = 1; i 

System.out.println("Square of " + i + " is: " + (i*i));

}

}

public static void main(String[] args) {

MethodReferenceThread test = new MethodReferenceThread();

test.createThread();

}

private void createThread() {

new Thread(this::runBody).start();    //方法引用

}

}

输出结果Square of 1 is: 1

Square of 2 is: 4

Square of 3 is: 9

Square of 4 is: 16

Square of 5 is: 25

Square of 6 is: 36

Square of 7 is: 49

Square of 8 is: 64

Square of 9 is: 81

super关键字示例class SuperReference {

public void runBody() {

for(int i = 1; i 

System.out.println("Square of " + i +" is: " + (i*i));

}

}

}

public class MethodRefSuperTest extends SuperReference {

public static void main(String[] args) {

MethodRefSuperTest test = new MethodRefSuperTest();

test.createThread();

}

private void createThread() {

new Thread(super::runBody).start();    //方法引用

}

}

输出结果Square of 1 is: 1

Square of 2 is: 4

Square of 3 is: 9

Square of 4 is: 16

Square of 5 is: 25

Square of 6 is: 36

Square of 7 is: 49

Square of 8 is: 64

Square of 9 is: 81

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值