获取多线程的方法有几种
答:传统的是继承thread类和实现runnable接口,java5以后又有实现callable接口和java的线程池获得
Callable和Runnable的对比
//实现Runnable接口
class MyThread1 implements Runnable{
@Override
public void run() {
}
}
//实现Callable接口
class MyThread2 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 200;
}
}
Callable接口与Runnable接口的区别
答:
- 是否有返回值
- 是否抛异常
- 落地方法不一样,一个是run,一个是call
Callable的使用:
```java public class CallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException {
}FutureTask<String> stringFutureTask = new FutureTask<String>(new Thread1());
new Thread(stringFutureTask).start();
System.out.println(stringFutureTask.get());
}
class Thread1 implements Callable{ @Override public String call() throws Exception { return “success”; } } ```