1. 继承Thread类 (Thread类实现了Runnable接口:public class Thread implements Runnable)
2. 实现Runnable接口
3. 使用Callable和Future
实例代码:
1. 继承Thread类
public class MyThreadDemo { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } } class MyThread extends Thread{ @Override public void run(){ //run方法 } }
2. 实现Runnable接口
(1) 方法一
public class MyThreadDemo { public static void main(String[] args) { Thread thread = new Thread(new Runnable(){ @Override public void run(){ //run方法 } }); thread.start(); } }
(2) 方法二
public class MyThreadDemo { public static void main(String[] args) { Runner one = new Runner(); Thread thread = new Thread(one); //都是接收了一个实现了Runnable的对象 thread.start(); } } class Runner implements Runnable{ @Override public void run(){ //run方法 } }
3. 使用Callable和Future
和Runnable接口不一样,Callable接口提供了一个call()方法作为线程执行体,call()方法比run()方法功能要强大。
(1). call()方法可以有返回值
(2). call()方法可以声明抛出异常
创建并启动有返回值的线程的步骤如下:
1】创建Callable接口的实现类,并实现call()方法,然后创建该实现类的实例(从java8开始可以直接使用Lambda表达式创建Callable对象)。
2】使用FutureTask类来包装Callable对象,该FutureTask对象封装了Callable对象的call()方法的返回值
3】使用FutureTask对象作为Thread对象的target创建并启动线程(因为FutureTask实现了Runnable接口)
4】调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CreateThread { public static void main(String[] args) throws InterruptedException, ExecutionException { // 第三种方式 FutureTask<String> ft = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { System.out.println("new Thread 3");// 输出:new Thread 3 return "aaaa"; } }); Thread t3 = new Thread(ft); t3.start(); String result = ft.get(); System.out.println(result);// 输出:aaaa } }
三种创建线程方式对比
实现Runnable和实现Callable接口的方式基本相同,不过是后者执行call()方法有返回值,前者线程执行体run()方法无返回值,因此可以把这两种方式归为一种,这两种方式与继承Thread类的方法之间的差别如下:
1、线程只是实现Runnable或实现Callable接口,还可以继承其他类。
2、这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。
3、如果需要访问当前线程,必须调用Thread.currentThread()方法。
4、继承Thread类的线程类不能再继承其他父类(Java单继承决定)。
注:一般推荐采用实现接口的方式来创建多线程