- Thread和Runnable区别
Thread
实际上是将线程和任务合并在了一起,Runnable
是将线程和任务分离,Thread
内部的run方法的具体实现如下,target
即使通过构造器传过来的参数,如果不为空则调用target
的run
方法。public void run() { if (target != null) { target.run(); } }
- Callable的使用
- 举例:调用
run
方法时,Callable
的call
方法就会被调用,并且结果会被保存起来。@Slf4j public class MyTest { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<String> task = new FutureTask<>(() -> { log.debug("entry the method"); Thread.sleep(1000); log.debug("exit the method"); return "Hello world"; }); new Thread(task).run(); System.out.println(task.get()); System.out.println(task.get()); } }
- 举例:调用
Java中的Thread、Runnable、Callable
最新推荐文章于 2022-12-31 00:36:40 发布
本文探讨了Thread和Runnable的区别,指出Thread将线程和任务整合,而Runnable分离两者。同时,介绍了Callable的使用实例,展示了如何通过FutureTask保存Callable的返回值。
摘要由CSDN通过智能技术生成