本文代码展示了在一个方法中,通过匿名内部类定义一个Thread,并Override它的run()方法,之后直接启动该线程。
下面的代码展示了在一个方法中,通过匿名内部类定义一个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();
}
}
更多免费相关学习经验请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html
如果心在远方,只需勇敢前行,梦想自会引路,