
public class CallerTask implements Callable<String> {
public String call() throws Exception
{ return "Hello,i am running!";
}
public static void main(String[] args) {
//创建异步任务
FutureTask<String> task=new FutureTask<String>(new CallerTask());
//启动线程
new Thread(task).start(); try {
//等待执行完成,并获取返回结果
String result=task.get(); System.out.println(result);
} catch (InterruptedException e)
{ e.printStackTrace();
} catch (ExecutionException e)
{ e.printStackTrace();
}
}
public class RunnableTask implements Runnable {
public void run()
{ System.out.println("Runnable!");
}
public static void main(String[] args) {
RunnableTask task = new RunnableTask();
new Thread(task).start();
}
上面两种都是没有返回值的,但是如果我们需要获取线程的执行结果,该怎么办呢?
实现Callable接口,重写call()方法,这种方式可以通过FutureTask获取任务执行的返回值
4.
为
什
么调用
start()
方法时会执
行run()
方法,那怎么
不
直接调用
run()
方法?
JVM
执
行start
方法,会先创建一条线程,由创建出来的新线程去执
行thread
的
run
方法,这才起到多线程的效果。