1. 继承Thread
缺点:无法获取线程的运算结果。
public class ThreadTest{
public static void main(String[] args){
Thread01 thread = new Thread01();
thread.start();
}
public static class Thread01 extends Thread{
public void run(){
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
}
2. 实现Runnable接口
缺点:无法获取线程的运算结果。
public class ThreadTest{
public static void main(String[] args){
Runnable01 runnable01 = new Runnable01();
Thread01 thread = new Thread01(runnable01);
thread.start();
}
public static class Runnable01 implement Runnable{
public void run(){
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
}
3. 实现Callable接口 + FutureTask
主线程可以获取线程的运算结果,可以处理异常,但是不利于控制服务器中的线程资源,会导致服务器资源耗尽。
public class ThreadTest{
public static void main(String[] args){
FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
Thread01 thread = new Thread01(futureTask );
thread.start();
Integer result = futureTask.get();
System.out.println("返回结果:" + result);
}
public static class Callable01 implement Callale<Integer>{
public void run(){
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}
}
}
4. 线程池
通过线程池性能稳定,也可以获取执行结果,并捕获异常,但是在业务复杂情况下,一个异步调用可能会依赖另一个异步调用的执行结果。
通过如下两种方式初始化线程池:
Executors.newFiexedThreadPool(3);
或者
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, workQueue, threadFactory,handler);