runnable和callable区别是什么?

        Runnable和Callable都是Java中用来实现多线程的接口。它们都表示可以在一个单独的线程中执行的代码块。然而,它们之间有一些区别。

  Runnable接口只有一个无返回值的run() 方法。它用于定义一个要在单独线程中执行的任务。当线程执行 run()方法时,它将运行任务,但不会返回任何结果。因此, Runnable接口更适合用于不需要返回结果的简单任务。

  Callable接口也是用于定义可以在单独线程中执行的任务,但是它具有不同的方法签名。它的call()方法可以返回一个值,并且可以抛出异常。因此, Callable接口更适合需要返回结果或可能抛出异常的任务。

1679886628616_runnable和callable有什么区别?.jpg

  下面是一个简单的代码演示,展示如何使用Runnable和Callable接口。

import java.util.concurrent.*;

public class Example {
    
    public static void main(String[] args) throws Exception {
        
        // Create a thread pool with a single thread
        ExecutorService executor = Executors.newSingleThreadExecutor();
        
        // Define a task using a Runnable
        Runnable task1 = () -> {
            System.out.println("Task 1 is running");
        };
        
        // Define a task using a Callable
        Callable<Integer> task2 = () -> {
            System.out.println("Task 2 is running");
            return 42;
        };
        
        // Submit the tasks to the executor
        Future<?> future1 = executor.submit(task1);
        Future<Integer> future2 = executor.submit(task2);
        
        // Wait for the tasks to complete and print their results
        System.out.println("Result of task 1: " + future1.get()); // Prints "Result of task 1: null"
        System.out.println("Result of task 2: " + future2.get()); // Prints "Result of task 2: 42"
        
        // Shut down the executor
        executor.shutdown();
    }
}

  在这个例子中,我们创建了一个单线程的线程池,并分别定义了一个Runnable和一个 Callable任务。我们将这些任务提交到线程池中,并使用Future对象来跟踪任务的执行和返回值。最后,我们等待任务完成并打印它们的结果。在任务完成后,我们关闭线程池。注意到,task1并不返回任何值,因此我们在等待结果时只能得到null。相反,task2返回一个整数值,因此我们可以通过future2.get()得到这个值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值