1、继承Thread,重写run方法
通过自定义一个类(比如MyThread),使其继承Thread类,然后对run方法进行重写,最后在main方法中new出MyThread实例,然后调用所继承的start方法创建一个线程(注意,仅仅创建MyThread并不是在系统中创建一个线程,只有调用start时,才创建出一个线程)
java
class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承Thread,重写run方法创建线程");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
2、实现Runnable接口,重写run方法
通过自定义一个类(这里起名为:MyRunnable)实现Runnable接口,重写run方法,最后在main方法new出MyRunnable实例和Thread实例,最后通过start方法创建并启动线程。
java
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口,重写run方法");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
3、使用匿名内部类创建Thread子类对象
直接创建Thread子类,同时实例化出一个对象,重写run方法,最后通过start方法创建并启动线程。
java
public class Main {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("使用匿名内部类创建 Thread 子类对象");
}
};
thread.start();
}
}