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() 有返回值,需要返回值必须使用

参考文章

  • https://javaguide.cn/java/concurrent/java-thread-pool-summary.html
  • https://blog.csdn.net/g6U8W7p06dCO99fQ3/article/details/126046723

你可能感兴趣的:(Java,java,jvm,面试)