Thread Runnable Callable Future 的区别

Thread

  • 通过继承 Thread 类,重写 run() 方法可以实现自定义线程
  • 使用 Thread 类存在缺点,就是 Java 只支持单继承
  • 继承 Thread 类无法获取线程执行的返回值
// 定义类继承 Thread 类,重写 run() 方法
public class CustomThread extends Thread {

    private final String name;

    public CustomThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread start: " + this.name + ",i = " + i);
        }
    }
}

// 测试定义的线程类
public class ThreadExample {
    public static void main(String[] args) {
        CustomThread ct1 = new CustomThread("ct1");
        CustomThread ct2 = new CustomThread("ct2");
        CustomThread ct3 = new CustomThread("ct3");

        ct1.start();
        ct2.start();
        ct3.start();
    }
}


Runnable

  • 通过实现 Runnable 接口,也可以实现自定义的线程
  • Java 中支持实现多个接口,相比继承 Thread 类,更加推荐通过接口方式实现
  • 通过实现 Runnable 接口,无法获得线程执行返回值
// 定义类实现 Runnable 接口,实现 run() 方法 
public class CustomRunnable implements Runnable {

    private final String name;

    public CustomRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread start : " + this.name + ",i= " + i);
        }
    }
}

// 调用 Runnable 接口,实例化线程对象,将接口实现作为参数传递
public class RunnableExample {

    public static void main(String[] args) {

        CustomRunnable cr1 = new CustomRunnable("cr1");
        CustomRunnable cr2 = new CustomRunnable("cr2");
        CustomRunnable cr3 = new CustomRunnable("cr3");

        Thread t1 = new Thread(cr1);
        Thread t2 = new Thread(cr2);
        Thread t3 = new Thread(cr3);

        t1.start();
        t2.start();
        t3.start();
    }

}

Callable

  • 通过实现 Callable 接口可以实现自定义线程池,并且可以获得返回值
import java.util.concurrent.Callable;

// 实现 Callable 接口,并且泛型执行返回值类型
public class CustomCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        String value = "test";
        System.out.println("Ready to work");
        Thread.currentThread().sleep(5000);
        System.out.println("task done");
        return value;
    }
}



import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

// 调用 Callable 接口,将 Callable 实现包装成 FutureTask 对象,再作为参数传给线程
public class CustomFutureTask {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        FutureTask<String> task = new FutureTask<>(new CustomCallable());

        new Thread(task).start();

        // 没执行完成,进入等待状态
        if (!task.isDone()) {
            System.out.println("task has not finished, please wait!");
        }

        // 执行完成获取返回结果
        System.out.println("task return: " + task.get());
    }
}

Future

  • 上面的例子是获取线程执行返回的结果,这个例子是获取线程池执行返回的结果
import java.util.concurrent.Callable;

// 实现 Callable 接口,定义返回值类型
public class CustomCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        String value = "test";
        System.out.println("Ready to work");
        Thread.currentThread().sleep(5000);
        System.out.println("task done");
        return value;
    }
}



import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

// 通过线程池调用 submit() 方法,传入 Callable 实现类,获取线程池执行的返回值
// 线程池的 execute() 方法执行,无法获取返回值
public class CustomFuture {

    public static void main(String[] args) {

        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        // submit()有返回值,execute()没有返回值
        Future<String> future = newCachedThreadPool.submit(new CustomCallable());

		// 线程池执行还没有返回结果
        if (!future.isDone()) {
            System.out.println("task has not finished, please wait!");
        }

        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            newCachedThreadPool.shutdown();
        }
    }

}

总结

  • 继承 Thread 类和实现 Runnable 接口实现都可以实现自定义线程,但是都无法获得线程执行的返回结果
  • 通过实现 Callable 接口,可以实现获取线程执行返回的结果
  • 实现自定义线程是 Thread 和 Runnable,而 Callable 接口是为弥补线程执行无法获取返回值或抛异常的缺点,这个就是它们的异同点
  • execute() 和 submit() 都属于线程池的方法,execute() 只能提交 Runnable 类型的任务
    • submit() 既能提交 Runnable 类型任务,也能提交 Callable 类型任务
    • 异常:
      execute() 会直接抛出任务执行时的异常,可以用 try、catch 来捕获,和普通线程的处理方式完全一致
      submit() 会吃掉异常,可通过 Future 的 get() 方法将任务执行时的异常重新抛出
    • 返回值:
      execute() 没有返回值
      submit() 有返回值,需要返回值必须使用

参考文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tytler

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值