public class ThreadTest {
public static void main(String[] args) {
System.out.println("main...start...");
Thread01 thread = new Thread01();
//启动线程
thread.start();
System.out.println("main...end...");
}
public static class Thread01 extends Thread{
@Override
public void run() {
System.out.println("当前线程:"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果:"+i);
}
}
}
/**
* 测试多线程的使用
*/
public class ThreadTest {
public static void main(String[] args) {
System.out.println("main...start...");
Runable01 runable01 = new Runable01();
new Thread(runable01).start();
System.out.println("main...end...");
}
public static class Runable01 implements Runnable{
@Override
public void run() {
System.out.println("当前线程:"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果:"+i);
}
}
}
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main...start...");
FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
new Thread(futureTask).start();
//等待整个异步方法执行完,获取返回结果
Integer integer = futureTask.get();
System.out.println("main...end..."+integer);
}
public static class Callable01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程:"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("运行结果:"+i);
return i;
}
}
}
问:为什么要使用线程池?
答:高并发系统下,内存空间是有限的,会消耗系统资源,导致系统崩溃。应该将所有的异步任务都交给线程池执行,做到资源控制。
public class ThreadTest {
//当前系统中池只有一两个,每个异步任务,直接提交给线程池
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main...start...");
executorService.execute(new Runable01());
System.out.println("main...end...");
}
}
总结:
1、线程池创建,准备好 core 数量的核心线程,准备接受任务
2、新的任务进来,用 core 准备好的空闲线程执行。
(1) 、core 满了,就将再进来的任务放入阻塞队列中。空闲的 core 就会自己去阻塞队 列获取任务执行
(2) 、阻塞队列满了,就直接开新线程执行,最大只能开到 max 指定的数量
(3) 、max 都执行好了。Max-core 数量空闲的线程会在 keepAliveTime 指定的时间后自动销毁。最终保持到 core 大小
(4) 、如果线程数开到了 max 的数量,还有新任务进来,就会使用 reject 指定的拒绝策 略进行处理
3、所有的线程创建都是由指定的 factory 创建的。
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
200,
10,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
先有 7 个能直接得到执行,接下来 50 个进入队列排队,在多开 13 个继续执行。现在 70 个 被安排上了。剩下 30 个默认拒绝策略。
查询商品详情页的逻辑比较复杂,有些数据还需要远程调用,必然需要花费更多的时间。
假如商品详情页的每个查询,需要如下标注的时间才能完成 那么,用户需要 5.5s 后才能看到商品详情页的内容。很显然是不能接受的。 如果有多个线程同时完成这 6 步操作,也许只需要 1.5s 即可完成响应。
CompletableFuture 提供了四个静态方法来创建一个异步操作。
1)CompletableFuture无返回值——runAsync
public static void main(String[] args){
System.out.println("main...start...");
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}, executorService);
System.out.println("main...end...");
}
2)CompletableFuture有返回值——supplyAsync
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main...start...");
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executorService);
Integer integer = future.get();
System.out.println("main...end..."+ integer);
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main...start...");
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executorService).whenComplete((res,exception)->{
//whenComplete虽然可以得到异常信息,但是没办法修改返回值
System.out.println("异步任务成功完成。结果是"+res+"异常是"+exception);
}).exceptionally(throwable -> {
//exceptionally可以感知,并且返回默认值
return 10;
});
Integer integer = future.get();
System.out.println("main...end..."+integer);
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main...start...");
/**
* 方法完成后的处理
*/
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executorService).handle((res,thr)->{
if( res != null ){
return res*2;
}
if( thr!= null ){
return 0;
}
return 0;
});
Integer integer = future.get();
System.out.println("main...end..."+integer);
}
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executorService).thenRunAsync(() -> {
System.out.println("任务2启动了");
});
System.out.println("main...end...");
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executorService).thenAcceptAsync((res) -> {
System.out.println("任务2启动了"+res);
},executorService);
System.out.println("main...end...");
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executor).thenApplyAsync((res) -> {
System.out.println("任务2启动了" + res);
return "hello" + res;
}, executor);
System.out.println("main...end..."+future.get());
/**
* 两个都完成
*/
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务一线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("任务一结束:" + i);
return i;
}, executor);
CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务二线程:" + Thread.currentThread().getId());
System.out.println("任务二结束");
return "hello";
});
//方式一
future01.runAfterBothAsync(future02,()->{
System.out.println("任务三开始");
},executor);
//方式二
future01.thenAcceptBothAsync(future02,(f1,f2)->{
System.out.println("任务三开始"+f1+"---"+f2);
},executor);
//方式三
CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
return f1 + ":" + f2 + "hahah";
}, executor);
System.out.println("main...end..."+future.get());
CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务一线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("任务一结束:" + i);
return i;
}, executor);
CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务二线程:" + Thread.currentThread().getId());
try {
Thread.sleep(3000);
System.out.println("任务二结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
});
future01.runAfterEitherAsync(future02,()->{
System.out.println("任务三开始");
},executor);
future01.acceptEitherAsync(future02,(res)->{
System.out.println("任务三开始");
},executor);
CompletableFuture<String> future = future01.applyToEitherAsync(future02, (res) -> {
return res.toString();
}, executor);
System.out.println("main...end..."+future.get());
CompletableFuture<String> futureImg = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的图片信息");
return "hello.jpg";
},executor);
CompletableFuture<String> futureAttr = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的属性信息");
return "黑色256g";
},executor);
CompletableFuture<String> futureDesc = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
System.out.println("查询商品的介绍");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "华为";
},executor);
//allOf
CompletableFuture<Void> allOf = CompletableFuture.allOf(futureImg, futureAttr, futureDesc);
//anyOf
CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureImg, futureAttr, futureDesc);
//allOf.get();//等待所有结果完成
anyOf.get();
System.out.println("main...end...");