Java创建线程有两种方法:
一、通过继承Thread类来实现,然后重写run方法
public class CreateThreadByExtendThread extends Thread{
@Override
public void run() {
System.out.println("通过继承Thread类来创建线程");
}
}
二、通过实现Runnable接口,然后实现run方法
public class CreateThreadByImplRunnable implements Runnable{
@Override
public void run() {
System.out.println("通过实现Runnable接口来创建线程");
}
}
然后在写一个测试类
public class Test {
public static void main(String[] args) {
CreateThreadByExtendThread thread1=new CreateThreadByExtendThread();
thread1.start();
System.out.println("########################");
CreateThreadByImplRunnable thread2=new CreateThreadByImplRunnable();
new Thread(thread2).start();
}
}
输出:
########################
通过继承Thread类来创建线程
通过实现Runnable接口来创建线程