Java直接定义了一个从根类Object中派生的Thread类。所以从java.lang.Thread类派生的直接子类或间接子类均为线程。构建Thread子类对象的步骤如下:
①构建Thread子类,重写其中的run()方法。
②创建线程对象。
③线程对象调用start()方法启动该线程。
代码示例:
public class Example11_1 extends Thread{
String threadId;
Example11_1(String threadId){
this.threadId=threadId;
}
public void run(){
System.out.println("Thread started:"+this.threadId);
for (int i = 0; i < 6; i++) {
System.out.print("i="+(i+1)+"\t");
}
System.out.println("Thread stooped:"+this.threadId);
}
}
public class ThreadTest {
public static void main(String[] args) {
System.out.println("Starting ThreadTest1");
Example11_1 t1=new Example11_1("thread1");
t1.start();
System.out.println("Starting ThreadTest2");
Example11_1 t2=new Example11_1("thread2");
t2.start();
System.out.println("Starting ThreadTest3");
Example11_1 t3=new Example11_1("thread3");
t3.start();
System.out.println("end");
}
}
某次运行图:
每次运行时可能不一样。
代码分析:
在ThreadTest类中不止有3个线程,至少有4个线程。其中3个线程在main()方法里面创建,还有一个线程执行main()方法。main()方法启动后,建立一个线程实例,在3个子线程获得执行之前完成自己的工作。
因此
Starting ThreadTest1
Starting ThreadTest2
Starting ThreadTest3
end
语句总是在最前面。