您的位置:首页 > 编程语言 > Java开发

Java 多线程之Thread类继承

2016-07-16 18:38 567 查看
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时进程中止。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: