1、匿名内部类的方式

 1 /**
2 *匿名内部类的方式启动线程
3 */
4 public class T2 {
5 public static void main(String[] args) {
6     //集成类的方式
7 new Thread(){
8 public void run(){
9 System.out.println("thread1 start ... ");
10 }
11 }.start();
12
13     //实现接口的方式
14 new Thread(new Runnable() {
15 @Override
16 public void run() {
17 System.out.println("thread2 start .... ");
18 }
19 }).start();
20
21 }
22 }

第1段相当于继承Thread的方式;第二段相当于实现Runnable的方式。

如果我们将上面两段代码合并呢?

 1 package com.yy.concurrent.base1;
2
3 /**
4 *匿名内部类的方式启动线程
5 */
6 public class T2 {
7 public static void main(String[] args) {
8
9
10 new Thread(new Runnable() {
11 @Override
12 public void run() {
13 System.out.println("runnable");
14 }
15 }){
16 public void run(){
17 System.out.println("sub");
18 }
19 }.start();
20
21 }
22 }

此时输出sub,此时相当于将一个实现了runnable接口的类对象传入Thread子类的构造方法,并且在这个子类中重写了run方法。因此原本的run()方法被覆盖。

2. Lambda方式

public class Test{
public static void main(String[] args) {
/*
匿名内部类的方式
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("nihao");
}
}).start();
System.out.println("你好"); */ //lambda的方式
new Thread(()-> {
for(int i = 1 ; i<100 ; i++){
System.out.println("It is a lambda function!");
} }).start(); }
}

此时相当于本文第一段代码中的实现接口的方式。

另外可参考:https://blog.csdn.net/Topdandan/article/details/78347865

最新文章

  1. HTML5移动开发学习笔记之CSS3基础学习
  2. 《黑客反汇编揭秘》(2e)推荐书单
  3. ASP.NET MVC 路由(二)
  4. Maximum Subarray
  5. 流程引擎Activiti系列:如何将kft-activiti-demo-no-maven改用mysql数据库
  6. 系统级IO实践学习记录
  7. php验证是否是中文
  8. python学习第七天
  9. setTimeout用法
  10. oracle多表关联删除数据表记录方法
  11. javascript (十) 变量
  12. Go语言string,int,int64 ,float转换
  13. centos 6.* 配置端口
  14. .net 获取远程访问的ip
  15. 必须要会的 50 个 React 面试题
  16. 强制SVN上传代码时添加日志
  17. EBS请求定义成菜单
  18. STL - 容器 - UnorderedSet(一)
  19. Git 的BUG小结
  20. pyDay11

热门文章

  1. js中function (res) {}与(res) =>{}的区别
  2. SpringCloud远程服务调用
  3. xpath解析案例
  4. [luogu5464]缩小社交圈
  5. [bzoj1432]Function
  6. 面向对象中static的理解(2) (单例模式)
  7. 调试:&#39;Object reference note set to an instance of an object.&#39;
  8. ICCV2021 | Swin Transformer: 使用移位窗口的分层视觉Transformer
  9. Ubuntu 18.04.5 LTS Ceph集群之 cephx 认证及使用普通用户挂载RBD和CephFS
  10. 【.NET 与树莓派】MPD 的 Mini-API 封装