线程创建方式由继承Thread类,实现Runnable接口,实现Callable接口通过FutureTask包装,通过线程池来创建
- 继承Thread类
Thread本质是实现Runnable接口的一个实例。实现如下:
/**
- 继承Thread类创建线程
*/
public class MyThread extends Thread {
/**
* 重写run()方法来实现自己的业务需求
*/
@Override
public void run() {
//打印线程名称及id
System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread().getId());
System.out.println("启动线程Thread");
}
}
public static void main(String[] args) {
//main 方法是一个线程
System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread().getId());
System.out.println("============调用其他线程start============");
//Thread方法创建线程
MyThread myThread = new MyThread();
myThread.start();
//Runnable方法创建线程
// MyRunnable myRunnable = new MyRunnable();
// new Thread(myRunnable).start();
System.out.println("============调用其他线程end==============");
}
- 实现Runnable接口
当一个类中已经继承了其他类,还要实现线程,就只能采用实现Runnable接口
/**
* 实现Runnable接口创建线程
*/
public class MyRunnable implements Runnable {
/**
* 重写run()方法来实现自己的业务需求
*/
@Override
public void run() {
//打印线程名称及id
System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread().getId());
System.out.println("启动线程Runnable");
}
}
public static void main(String[] args) {
//main 方法是一个线程
System.out.println(Thread.currentThread().getName() + "\t" + Thread.currentThread