您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java:使用匿名内部类在方法内部定义并启动线程

2024/2/18 13:23:15发布17次查看
下面的代码展示了在一个方法中,通过匿名内部类定义一个thread,并override它的run()方法,之后直接启动该线程。
这样的代码可用于在一个类内部通过另起线程来执行一个支线任务,一般这样的任务并不是该类的主要设计内容。
package com.zj.concurrency; 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)
更多java:使用匿名内部类在方法内部定义并启动线程。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product