获取多线程的方法有几种

答:传统的是继承thread类和实现runnable接口,java5以后又有实现callable接口和java的线程池获得

Callable和Runnable的对比

  1. //实现Runnable接口
  2. class MyThread1 implements Runnable{
  3. @Override
  4. public void run() {
  5. }
  6. }
  7. //实现Callable接口
  8. class MyThread2 implements Callable<Integer>{
  9. @Override
  10. public Integer call() throws Exception {
  11. return 200;
  12. }
  13. }

Callable接口与Runnable接口的区别

答:

  1. 是否有返回值
  2. 是否抛异常
  3. 落地方法不一样,一个是run,一个是call

    Callable的使用:

    ```java public class CallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException {
    1. FutureTask<String> stringFutureTask = new FutureTask<String>(new Thread1());
    2. new Thread(stringFutureTask).start();
    3. System.out.println(stringFutureTask.get());
    }

}

class Thread1 implements Callable{ @Override public String call() throws Exception { return “success”; } } ```