多线程一共有三种创建方式
- 继承Thread类
- 实现Runable接口
- 实现Callable接口
1. Thread类
Thread类是java自带的关于线程的类,其本身是实现了Runable类。

实现多线程,第一个方法的步骤如下:
- 声明一个Thread类的子类,然后重写run方法,建立子类的实例;
- 并调用start方法开启线程。(注意,实例调用run方法就仅仅是调用run方法,并没有开启多线程)
如下:
public class TestThread extends Thread{
@Override
public void run(){
// run方法为一个thread线程的主体,这里我们重写了
for(int i=0; i<100; i++){
System.out.println("run线程--"+i);
}
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.run(); // 调用run方法仅仅是run方法,没有开启线程
testThread.start(); // 调用start方法才能开启线程
// 当一个Java程序启动的时候,会有一个线程立即开始运行,
// 这个线程通常被我们叫做程序中的主线程,
// 因为它是在我们程序开始的时候就被执行的线程。
// main方法,是 主线程
for(int i=0; i<100; i++){
System.out.println("main线程--"+i);
}
}
}

2. Runable接口
多线程第二种实现方法是实现Runable接口。
- 实现runable接口,重写run方法;
- 创建runable接口实现类的实例;
- 需要将runable接口的实现类丢入到Thread类的构造方法中,再调用start方法
第三步丢入构造方法是因为Thread的构造方法的形参有一个Runable实例化的对象

public class TestThread2 implements Runnable{
@Override
public void run(){
for(int i=0; i<100; i++){
System.out.println("run线程--"+i);
}
}
public static void main(String[] args) {
TestThread2 testThread2 = new TestThread2(); // Runable实现类的对象
Thread thread = new Thread(testThread2);
thread.start(); // 调用start方法开启线程
// main线程 主线程
for(int i=0; i<100; i++){
System.out.println("main线程--"+i);
}
}
}
3. 实现Callable接口
步骤:
网友评论