启动线程的5种方法:
1. new MyThread().start()
2. new Thread(r).start()
3. new Thread(lamda).start()
4. ThreadPool...
5. Future Callable and FutureTask
示例:
import java.util.concurrent.*;
public class T02_HowToCreateThread {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("Hello MyThread!");
}
}
static class MyRun implements Runnable {
@Override
public void run() {
System.out.println("Hello MyRun!");
}
}
//带返回值的线程
static class Mycall implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("hello mycall");
return "success";
}
}
//启动线程的5种方式
public static void main(String[] args) throws Exception{
//第1 种启动线程
new MyThread().start();
//第2种启动线程
new Thread(new MyRun()).start();
//第3种启动线程
new Thread(()->{
System.out.println("Hello Lambda!");
}).start();
//第4 线程池的方式启动线程
ExecutorService service = Executors.newCachedThreadPool();
service.execute(()->{
System.out.println("hello threadpool");
});
//第5.1 带返回值的线程,利用线程池来执行
Future<String> future = service.submit(new Mycall());
future.get();//这个方法是阻塞的,获取返回值
//第5.2.1 带返回值的线程,利用FutureTask来执行的第一种写法
FutureTask<String> task = new FutureTask<>(new Mycall());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());//获取返回值
//第5.2 2带返回值的线程,利用FutureTask来执行的第二种写法
Thread t = new Thread(new FutureTask<String>(new Mycall()));
t.start();
service.shutdown();
}
}
这么多种启动线程的方式,其实本质上及是new 一个Tread对象,底层代码都是这样的。