public class RunnableTest
implements Runnable {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
//使用Runnable接口的类,必须手工创建一个线程
new Thread(new RunnableTest(i)).start();
}
}
private static int threadCount = 0;
private int threadNum;
private int i = 5;
//Runnable的构造函数,每次执行线程计数器threadCount加一
public RunnableTest(int threadNo) {
threadNum = threadNo;
threadCount++;
System.out.println("创建线程" + threadNum);
}
public void run() {
while (true) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("线程" + threadNum + " ,计数" + i);
if (--i == 0)
return;
}
}
}
Java线程创建示例
本文介绍了一个使用Java Runnable接口创建线程的具体示例。通过继承Runnable接口并实现run()方法,可以定义线程的任务。此外,文章展示了如何启动这些线程,并控制线程的行为,包括计数和中断处理。

被折叠的 条评论
为什么被折叠?



