知识点记录-高并发JAVA多线程(thread runnable callable executors future completablefuture)
package com.thread;
import java.util.concurrent.*;
//多线程,可用于优化业务功能流程执行效率
public class JavaThread {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
//使用thread类
Thread1 thread1 = new Thread1();
thread1.start();
Thread thread = new Thread1();
thread.start();
//runnable接口
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("使用runnable接口创建线程");
}
}).start();
//使用runnable接口的lambda表达式
new Thread(() -> {
System.out.println("使用runnable接口的lambda表达式");
}).start();
//callable接口
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
return "使用callable接口创建线程";
}
};
//创建线程池 多个功能使用多个线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
ExecutorService executorService1 = new ThreadPoolExecutor(5, 50,
5000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(500),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
Future<String> future = executorService.submit(callable);
System.out.println(future.get(5, TimeUnit.SECONDS));
//callabe接口的lambda表达式
System.out.println(executorService.submit(() -> "使用callabe接口的lambda表达式").get());
//多线程流.JDK8接口CompletableFuture
CompletableFuture completableFuture = new CompletableFuture();
completableFuture.complete("完成completableFuture");
System.out.println("返回值completableFuture.join=" + completableFuture.join());
System.out.println("返回值completableFuture.ge