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()); } }

京公网安备 11010502036488号