1. 继承Thread类
/**
* 继承 Thread 实现多线程方式
*/
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("hello!");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}总结:重写的是run()方法,而不是start()方法,但是占用了继承的名额,Java中的类是单继承的。
讲到单继承,我们应该注意,java中的接口是可以多继承的
2. 实现Runnable接口
/**
* 实现 Runnable 接口创建多线程方式
*/
public class MyThread02 implements Runnable {
public void run() {
System.out.println("hello!");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyThread02());
thread.start();
}
}总结:实现Runnable接口,实现run()方法,使用依然要用到Thread,这种方式更常用
有时候,我们会直接使用匿名内部类的方式或者Lambda表达式的方式:
public class MyThread05 {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("hello!");
}
});
thread.start();
}
}public class MyThread06 {
public static void main(String[] args) {
Thread thread = new Thread(() -> System.out.println("Hello!"));
thread.start();
}
}3. 实现Callable接口
/**
* 实现 Callable 接口实现多线程方式
*/
public class MyThread03 implements Callable<String> {
public String call() throws Exception {
return "Hello world!";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<String>(new MyThread03());
Thread thread = new Thread(futureTask);
thread.start();
String result = futureTask.get();
System.out.println(result);
}
}总结:实现Callable接口,实现call()方法,得使用Thread+FutureTask配合,这种方式支持拿到异步执行任务的结果
4. 利用线程池来创建线程
/**
* 使用线程池方式创建线程
*/
public class MyThread04 implements Runnable{
public void run() {
System.out.println("hello");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new MyThread04());
}
}总结:实现Callable接口或者Runnable接口都可以,由ExecutorService来创建线程
注意,工作中不建议使用Executors来创建线程池
总结
以上几种方式,底层都是基于Runnable。