1.继承Thread,重写run方法
class ThreadExt extends Thread {
@Override
public void run() {
System.out.println("多线程"+this.getName());
try{
sleep(1000L);
System.out.println("多线程"+this.getName()+"睡眠结束");
}catch (Exception e) {
}
}
}
2.实现Runnable接口与,重写run方法
class ThreadImpRunnable implements Runnable{
@Override
public void run() {
System.out.println("Runnable start");
try{
Thread o = new Thread();
o.sleep(3000L);
System.out.println("Runnable睡眠结束");
}catch (Exception e) {
}
}
}
3.实现Callable接口,重写call方法
class ThreadImpCallable implements Callable<String>{
@Override
public String call() throws Exception{
System.out.println("Callable start");
try{
Thread o = new Thread();
o.sleep(3000L);
System.out.println("Callable睡眠结束");
}catch (Exception e) {
}
return "callable返回值";
}
}
主线程如何调用
public class ThreadExtend {
public static void main(String[] args) throws Exception{
//1 继承Thread
System.out.println("主线程开始");
ThreadExt threadExtend = new ThreadExt();
threadExtend.start();
//2 实现Runnable接口
Long start1 = System.currentTimeMillis();
Thread thread = new Thread(new ThreadImpRunnable());
thread.start();
System.out.println("runnable执行花了"+(System.currentTimeMillis()-start1));
//3 实现Callable接口
Long start = System.currentTimeMillis();
ThreadImpCallable callableDemo = new ThreadImpCallable();
FutureTask futureTask = new FutureTask<>(callableDemo);
Thread threadcall = new Thread(futureTask);
threadcall.start();
System.out.println("callable开始执行花了"+(System.currentTimeMillis()-start));
String name = (String) futureTask.get(); //获取返回值
System.out.println(name);
System.out.println("callable执行完得到结果花了"+(System.currentTimeMillis()-start));
}
}
结论
3种多线程方式执行start之后,都是以多线程的方式同时开始的,但Callable接口想要获取返回值,需要阻塞到方法执行完