第一种方法:继承Thread类
public class NewThread extends Thread {
public void run()
{
for(int i=0;i<20;i++)
{
System.out.println(i);
}
}
}
public class Test {
public static void main(String[] args) {
NewThread t = new NewThread();
t.start();
}
}
第二种方法:实现Runnable接口
public class NewThread implements Runnable {
@Override
public void run() {
for(int i=0;i<20;i++)
{
System.out.println(i);
}
}
}
public class Test3 {
public static void main(String[] args) {
NewThread n = new NewThread();
Thread t = new Thread(n);
t.start();
}
}
当然,有一种比较骚气的写法是这样:
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<20;i++)
{
System.out.println(i);
}
}
}).start();
}
直接定义了一个线程并且开启了它。
两种方法的不同
推荐使用实现Runnable接口的方式来创建线程,因为java中不支持多继承,也就是说,第一种方法中继承了Thread类之后就没法再去继承别的类了,而java支持实现多个接口,使用第二种方式就完全不会有这种问题。同时,使用实现接口的方式创建的线程可以共享统一资源,在某些情况下保证线程安全。