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时进程中止。
线程并不是按照它们创建时的顺序执行的。事实,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时进程中止。
相关文章推荐
- Java Enum 枚举类型
- Java中进制转换
- Java集合(3):Vector && Stack
- mybatis-generator maven 生成映射文件
- eclipse+webservice开发实例
- Ubuntu 程序“java”已包含在下列软件包中
- Java 基础之(七) 继承
- 【spring 3】AOP:静态代理
- 【spring 3】AOP:静态代理
- 【Java源码分析】ArrayList源码分析
- java LinkedList
- JavaWeb核心编程之(三.2)Servlet配置
- java怎么用一行代码初始化ArrayList
- SpringMVC类型转换器、属性编辑器
- spring4.x注解详述
- java编程 中流对象选取规律
- Java复习之数字与字符串
- Spring 3.x jar 包详解 与 依赖关系
- spring mvc JSON实现方式
- Struts2动态方法调用(DMI)