Java创建线程的方法

参考文章:Java创建线程及配合使用Lambda
总体而言创建线程的方式有三种:

  • 继承Thread类创建线程类
  • 通过Runnable接口创建线程类
  • 通过Callable和Future创建线程

继承Thread类创建线程类

public class FirstThreadTest extends Thread {
    int i = 0;

    // 重写run方法,run方法的方法体就是现场执行体
    public void run() {
        for (; i < 5; i++) {
            System.out.println(getName() + "  " + i);
        }
    }
}

调用start()方法启动线程。

通过Runnable接口创建线程类

public class RunnableThreadTest implements Runnable {
    private int i;

    public void run() {
        for (i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

调用start()方法启动线程。

通过Callable和Future创建线程

1、创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
2、创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。(FutureTask是一个包装器,它通过接受Callable来创建,它同时实现了Future和Runnable接口。)
3、使用FutureTask对象作为Thread对象的target创建并启动新线程。
4、调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
代码如下:

public class CallableThreadTest implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        return i;
    }

    public static void main(String[] args) {
        CallableThreadTest ctt = new CallableThreadTest();
        FutureTask<Integer> ft = new FutureTask<>(ctt);
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 2) {
                new Thread(ft, "有返回值的线程").start();
            }
        }
        try {
            System.out.println("子线程的返回值:" + ft.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

}
posted on 2019-11-04 19:18  Mrnx  阅读(161)  评论(0编辑  收藏  举报