一、所有的多线程启动都是有Thread的start方法启动
继承Thread类
使用:.继承Thread类实现多线程,jdk代码中Thread类也实现了Runnable接口,需要重新run(),通start方法启动多线程
缺点:继承Thread耦合性比较强,java只能单继承不利于扩展
实现Runnable接口
使用:实现Runnable类,重新run()方法,并把Runnable实例传递给Thread对象,Thread的start方法调用run方法再调用Runnable实例的run方法启动线程
缺点:没有返回值、不知道多线程执行情况
实现Callable接口
使用:jdk1.5 之后 实现Callable接口,并重写call方法(返回的是泛型)。把Callable实例传递给futureTask对象,再把futureTask实例传递给Thread对象
示例如下
package thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyALLThread {
public static void main(String [] arge) throws InterruptedException, ExecutionException{
MYThread t1=new MYThread();
MYRunnable runable=new MYRunnable();
Thread t2=new Thread(runable);
FutureTask task=new FutureTask(new MYCallable());
Thread t3=new Thread(task);
t1.start();
t2.start();
t3.start();
System.out.println(task.get());
}
static class MYThread extends Thread{
@Override
public void run(){
System.out.println("MYThread runing....");
}
}
static class MYRunnable implements Runnable{
@Override
public void run() {
System.out.println("MYRunnable runing...");
}
}
static class MYCallable implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("MYCallable runing...");
return "执行完成。。。";
}
}
}