使用匿名内部类和lamda的方式创建线程
2024-09-06 02:16:53
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
最新文章
- HTML5移动开发学习笔记之CSS3基础学习
- 《黑客反汇编揭秘》(2e)推荐书单
- ASP.NET MVC 路由(二)
- Maximum Subarray
- 流程引擎Activiti系列:如何将kft-activiti-demo-no-maven改用mysql数据库
- 系统级IO实践学习记录
- php验证是否是中文
- python学习第七天
- setTimeout用法
- oracle多表关联删除数据表记录方法
- javascript (十) 变量
- Go语言string,int,int64 ,float转换
- centos 6.* 配置端口
- .net 获取远程访问的ip
- 必须要会的 50 个 React 面试题
- 强制SVN上传代码时添加日志
- EBS请求定义成菜单
- STL - 容器 - UnorderedSet(一)
- Git 的BUG小结
- pyDay11
热门文章
- js中function (res) {}与(res) =>{}的区别
- SpringCloud远程服务调用
- xpath解析案例
- [luogu5464]缩小社交圈
- [bzoj1432]Function
- 面向对象中static的理解(2) (单例模式)
- 调试:&#39;Object reference note set to an instance of an object.&#39;
- ICCV2021 | Swin Transformer: 使用移位窗口的分层视觉Transformer
- Ubuntu 18.04.5 LTS Ceph集群之 cephx 认证及使用普通用户挂载RBD和CephFS
- 【.NET 与树莓派】MPD 的 Mini-API 封装