文章目录
- 一、线程的三种创建方式
- 1.继承Thread
- 2.实现Runable接口
- 3.实现Callable接口
- 二、三种创建方式的优缺点
- 1.使用Runnable接口比使用继承Thread的优势
- 2.使用Thread类
- 3.使用Runnable接口
- 4.使用Callable接口
一、线程的三种创建方式
1.继承Thread类方式
创建一个类继承Thread类,重写run()方法,在主线程中创建此类的对象,调用对象的start()方法,可启动线程
public class Demo4 {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("aaaaa");
}
}
}
2.实现Runnable接口
创建一个类实现Runnable接口,在主线程中创建这个类的对象实例,新创建一个线程并调用start()方法启动线程&#