Java代码中Runnable与Callable相同点及不同点是什么呢?
下文笔者将讲述多线程开发中,常用的Runnable同Callable接口的相同点和不同点的相同之处及不同之处的简介说明,如下所示:
两者相同点: Callable和Runnable都是接口 Callable和Runnable都可以应用于Executors 都可以编写多线程程序 都采用Thread.start()启动线程 两者不同点: Callable要实现call方法,Runnable要实现run方法 call方法可以返回值,run方法不能 Callable接口的call()方法允许抛出异常;Runnable的run()方法异常只能在内部消化,不能往上继续抛 Callalble接口支持返回执行结果,需要调用FutureTask.get()得到,此方法会阻塞主进程的继续往下执行,如果不调用不会阻塞 Runnable接口在jdk1.1就有了,Callable在Jdk1.5才有接口示例
----Callable接口
public interface Callable<V> {
V call() throws Exception;
}
----Runnable接口
public interface Runnable {
public abstract void run();
}
例1:Callable示例分析
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableAndFuture {
public static void main(String[] args) {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(6000);
return new Random().nextInt();
}
};
FutureTask<Integer> future = new FutureTask<>(callable);
new Thread(future).start();
try {
Thread.sleep(1000);
System.out.println("hello java265.com");
System.out.println(future.isDone());
System.out.println(future.get());
System.out.println(future.isDone());
System.out.println("hello end");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
例2:Callable示例分析
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
new Thread(ft, "有返回值的线程").start();
System.out.println("子线程的返回值" + ft.get());
}
@Override
public Integer call() {
int i;
for (i = 0; i < 10; i += 2) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


