方式一:继承Thread类

/**
 * 创建线程方式1:继承Thread类,实现run方法,调用start方法启动线程
 * @author Lenovo
 */
public class MyThread extends Thread{
	@Override
	public void run() {
		System.out.println("当前运行线程:" + Thread.currentThread().getName());
	}
	public static void main(String[] args) {
		MyThread mt = new MyThread();
		mt.setName("Extends_Thread_thread");
		mt.start();
	}
}

方式二:实现Runnable接口

**
 * 创建线程方式二:实现Runnable接口,覆写run方法,将实例化对象传入new Thread()方法中
 * @author Lenovo
 */
public class MyThreadRunable implements Runnable{
	@Override
	public void run() {
		System.out.println("当前运行线程:" + Thread.currentThread().getName());
	}
	public static void main(String[] args) {
		Thread mtr = new Thread(new MyThreadRunable());
		mtr.setName("Thread_Runnable");
		mtr.start();
	}
}

方式一和方式二,推荐使用方式二,因为:

1、Java编程语言只能继承一个类,一旦继承了Thread就不能再继承其他类,限制了类的继承特性;

2、实现Runnable接口,便于类的共享

基于方式二,演变出如下三种实现线程的方法。

方法三:匿名内部类,在Thread实例化方法中传入Runnable接口的实例化对象

/**
 * 实现线程的方式三:匿名内部类,在实例化Thread的时候传入实例化Runnable接口的类,与实现Runnable接口一样
 * @author Lenovo
 */
public class MyThreadClass {
	public static void main(String[] args) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("运行线程:" + Thread.currentThread().getName());	
			}
		});
		t.setName("class_thread");
		t.start();
	}
}

方法四:Lamda表达式

/**
 * Lamda表达式
 * @author Lenovo
 */
public class MyThreadLamda {
	public static void main(String[] args) {
		Thread t = new Thread(()->{
			System.out.println("运行线程: " + Thread.currentThread().getName());
		});
		t.setName("lamda_thread");
		t.start();
	}

}

方法五:线程池

/**
 * 线程池
 * @author Lenovo
 */
public class MyThreadPool {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newSingleThreadExecutor();	
		executorService.execute(()->{
			System.out.println("运行线程:" + Thread.currentThread().getName());
		});
	}
}