Thread类中最重要的方法是run(),run()是属于那些会与程序中其他线程“并发”或“同时”执行的代码。
线程并不是按照它们创建时的顺序执行的。事实,CPU处理一个现有线程集的顺序是不确定的,除非我们使用Thread中的setPriority()方法调整它们的优先级。
public class SimpleThread extends Thread{
private int countDown = 5;
private int threadNumber;
private static int threadCount = 0;
public SimpleThread(){
threadNumber = ++threadCount;
System.out.println("Making " + threadNumber);
}
public void run(){
while(true){
System.out.println("Thread " + threadNumber + "(" + countDown + ")");
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i < 5; i++)
new SimpleThread().start();
System.out.println("All Thread Started");
}
}
上面这个例子中SimpleThread继承了Thread类,并覆盖了run()方法,每通过一次循环,计数就减一,计数为0时进程中止。