1.获得多线程的方法有几种?
传统
的是继承
thread
类和实现
runnable
接口,
java5
以后又有实现
callable
接口
和
java
的线程池
获得
2.与 Runnable 对比?
import java.util.concurrent.Callable;
//创建类MyThread实现Runnable接口
public class MyThread implements Runnable {
@Override
public void run() {
}
}
//创建类MyThread2实现Callable接口
class MyThread2 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return null;
}
}
问题:callable 接口与 runnable 接口的区别?
答:(1)是否有返回值
(2)是否抛异常
(3)落地方法不一样,一个是
run
,一个是
call
程序代码
?
import java.util.concurrent.Callable;
//创建类MyThread实现Runnable接口
public class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(4000);
System.out.println(Thread.currentThread().getName() + " ******come in call");
return 200;
}
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread());
new Thread(ft, "AA").start();
System.out.println(Thread.currentThread().getName() + "----main");
Integer result = ft.get();
System.out.println("**********result: "+result);
}
}
|