下面的代码展示了在一个方法中,通过匿名内部类定义一个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

最新文章

  1. java多态的理解
  2. 整整十年 - Agent Framework for TypeScript 2.0
  3. img
  4. 微信自定义分享到朋友圈API
  5. Delphi经验总结(3)
  6. PHP函数补完:stream_context_create()模拟POST/GET
  7. 第三篇T语言热键启动方法
  8. iis8 默认不支持svc解决方法
  9. XML注入介绍--XXE,XEE,xpath等
  10. Educational Codeforces Round 1 E. Chocolate Bar 记忆化搜索
  11. Unity3d本地存储
  12. 你所不知道的C++
  13. .net web 开发平台- 表单设计器 一(web版)
  14. C语言qsort函数算法性能测试
  15. 【翻译】了解ASP.NET MVC中的Ajax助手
  16. vscode restclient 插件
  17. nodejs的package.json依赖dependencies中 ^ 和 ~ 的区别
  18. JAVA的第一次作业
  19. Python&#160;再谈变量作用域与变量引用
  20. JQuery 节点监听

热门文章

  1. Linux下打包tar.gz
  2. BI之SSIS入门最新版Visual Studio调试技巧
  3. .9-浅析express源码之请求处理流程(2)
  4. spark on yarn 运行问题记录
  5. Python:操作数据库
  6. Response ServletContext 中文乱码 Request 编码 请求行 共享数据 转发重定向
  7. c++ 文件操作详解
  8. Kinect SDK2.0 + OpenCV 3.0 抠人,换背景
  9. WeihanLi.Npoi
  10. MySQL/MariaDB 在插入数据的时候提示 Incorrect string value