定义一个类继承Thread类,重写Thread类的run()方法,创建所定义的线程类的实例化对象,调用该对象的start()方法启动线程。线程启动后自动调用run()方法。
public class Test extends Thread {
static long s,m = 1;
public static void main(String[] args){
Test t1 = new Test();
t1.start();
for(int i = 1; i < 10000; i++)
s += i;
System.out.println("s = " +s);
System.out.println("m = " +m);
}
public void run() {
for(int j = 1; j<=10; j++)
m *= j;
}
}
定义一个类实现Runnable接口,重写Thread类的run()方法,用已经实现了Runnable接口的对象创建一个Thread对象,调用该对象的start()方法启动线程。
public class Test implements Runnable {
static long s,m = 1;
public static void main(String[] args){
Thread t1 = new Thread(new Test());
t1.start();
for(int i = 1; i < 10000; i++)
s += i;
System.out.println("s = " +s);
System.out.println("m = " +m);
}
public void run() {
for(int j = 1; j<=10; j++)
m *= j;
}
}
这里的Thread类的构造方法:
Thread(Runnable threadOb,String threadName);
threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字。