电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

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


发布日期:2018/11/12
 

本文代码展示了在一个方法中通过匿名内部类定义一个Thread并Override它的run()方法之后直接启动该线程

下面的代码展示了在一个方法中通过匿名内部类定义一个Thread并Override它的run()方法之后直接启动该线程

这样的代码可用于在一个类内部通过另起线程来执行一个支线任务一般这样的任务并不是该类的主要设计内容

package ncurrency;

public class StartFromMethod {

private Thread t;

private int number;

private int count = ;

public StartFromMethod(int number) {

thisnumber = number;

}

public void runTask() {

if (t == null) {

t = new Thread() {

public void run() {

while (true) {

Systemoutprintln(Thread + number + run + count

+ time(s));

if (++count == )

return;

}

}

};

tstart();

}

}

public static void main(String[] args) {

for (int i = ; i < ; i++)

new StartFromMethod(i)runTask();

}

}

结果

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

Thread run time(s)

上一篇:详解abstract class和interface的本质

下一篇:避免使用finalizer()函数