Java实现多线程的方式
继承Thread类
重写run方法,使用时,调用start方法
实现Runnable接口
适用于已经继承过类的情况,实现run方法,使用时,
new Thread(runnable的实例).start()
实现Callable接口
实现Callable接口,通过FutureTask包装器来创建Thread线程。
- 创建实现Callable接口的实例
- 封装任务为FutureTask
- Thread开启线程
//创建线程任务
Callable<Integer> callable = ()->{
System.out.println("线程任务开始执行了");
Thread.sleep(2000);
return 1;
};
//将任务封装为FutureTask
FutureTask<Integer> task = new FutureTask<>(callable);
//开启线程
new Thread(task).start();
System.out.println("线程启动之后,结果返回之前");
//拿到结果
Integer res = task.get();
System.out.println("主线程中异步任务执行的结果为:"+res);
}
结果
使用ExecutorService、Callable、Future
注意,Future的get方法是阻塞的,即线程无返回结果,get方法会一直等待。
package com.Concurrent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class myThread4 {
public static void main(String[] args) throws Exception{
System.out.println("主程序开始运行");
Date startTime = new Date();
int taskSize = 5;
//创建一个线程池
ExecutorService executorService = Executors.newFixedThreadPool(taskSize);
//创建多个有返回值的任务
List<Future> futureList = new ArrayList<Future>();
for(int i=0;i<taskSize;i++){
Callable callable = new MyCallable(i);
//执行任务获取Future对象
Future future = executorService.submit(callable);
futureList.add(future);
}
//关闭线程池
executorService.shutdown();
//获取所有并发任务的运行结果
for(Future future:futureList){
System.out.println(">>> "+future.get().toString());
}
Date endTime = new Date();
System.out.println("主程序结束运行,程序运行耗时 "+(endTime.getTime()-startTime.getTime())+" 毫秒");
}
}
class MyCallable implements Callable<Object>{
private int taskNum;
MyCallable(int taskNum){
this.taskNum = taskNum;
}
public Object call()throws Exception{
System.out.println(">>> "+taskNum + " 线程任务启动");
Date startTime = new Date();
Thread.sleep(1000);
Date endTime = new Date();
long time = endTime.getTime()-startTime.getTime();
System.out.println("--- "+taskNum+" 线程任务终止");
return taskNum + "线程任务返回运行结果,当前任务耗时 "+time+" 毫秒";
}
}
结果