Java:使用匿名内部类在方法内部定义并启动线程
2024-09-30 13:29:04
下面的代码展示了在一个方法中,通过匿名内部类定义一个Thread,并Override它的run()方法,之后直接启动该线程。
这样的代码可用于在一个类内部通过另起线程来执行一个支线任务,一般这样的任务并不是该类的主要设计内容。
public class StartFromMethod { private Thread t; private int number; private int count = 1; public StartFromMethod(int number) { this.number = number; } public void runTask() { if (t == null) { t = new Thread() { public void run() { while (true) { System.out.println("Thread-" + number + " run " + count + " time(s)"); if (++count == 3) return; } } }; t.start(); } } public static void main(String[] args) { for (int i = 0; i < 5; i++) new StartFromMethod(i).runTask(); } }
结果:
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/70056
最新文章
- java多态的理解
- 整整十年 - Agent Framework for TypeScript 2.0
- img
- 微信自定义分享到朋友圈API
- Delphi经验总结(3)
- PHP函数补完:stream_context_create()模拟POST/GET
- 第三篇T语言热键启动方法
- iis8 默认不支持svc解决方法
- XML注入介绍--XXE,XEE,xpath等
- Educational Codeforces Round 1 E. Chocolate Bar 记忆化搜索
- Unity3d本地存储
- 你所不知道的C++
- .net web 开发平台- 表单设计器 一(web版)
- C语言qsort函数算法性能测试
- 【翻译】了解ASP.NET MVC中的Ajax助手
- vscode restclient 插件
- nodejs的package.json依赖dependencies中 ^ 和 ~ 的区别
- JAVA的第一次作业
- Python&#160;再谈变量作用域与变量引用
- JQuery 节点监听
热门文章
- Linux下打包tar.gz
- BI之SSIS入门最新版Visual Studio调试技巧
- .9-浅析express源码之请求处理流程(2)
- spark on yarn 运行问题记录
- Python:操作数据库
- Response ServletContext 中文乱码 Request 编码 请求行 共享数据 转发重定向
- c++ 文件操作详解
- Kinect SDK2.0 + OpenCV 3.0 抠人,换背景
- WeihanLi.Npoi
- MySQL/MariaDB 在插入数据的时候提示 Incorrect string value