多线程
为了提高CPU利用率,减少CPU的空闲时间,提高程序运行速度而引入的概念。一般来说,一个单核处理器只能同时运行一个线程,双核则两个线程,但超线程技术的引入改变了这一点。例:I9 13900HX 为24核心32线程处理器
Java多线程的实现方式
继承Thread
1 2 3 4 5 6 7 8 9
| Thread thread01 = new Thread01(); thread01.start();
public static class Thread01 extends Thread{ @Override public void run(){ } }
|
实现Runnable接口
1 2 3 4 5 6 7 8 9
| Runnable01 runnable01 = new Runnable01(); new Thread(runnable01).start();
public static class Runnable01 implements Runnable{ @Override public void run(){ } }
|
实现Callable接口
1 2 3 4 5 6 7 8 9 10 11
| FutureTask<Integer> futureTask = new FutureTask<>(new Callable01()); new Thread(futureTask).start(); futureTask.get();
public static class Callable01 implements Callable<Integer>{ @Override public Integer call() throws Exception{ return 1; } }
|
线程池
1 2 3 4 5 6 7
| private static ExecutorService service = Executors.newFixedThreadPool(10); private static ExecutorService service = Executors.newCacheThreadPool(10); private static ExecutorService service = Executors.newSingleThreadExecutor(); private static ExecutorService service = Executors.newScheduledThreadPool();
service.execute(); service.submit();
|
原生创建线程池
1 2 3 4 5 6 7 8 9 10 11 12
|
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor();
|
线程池串行化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
thenRunAsync thenAcceptAsync thenApplyAsync
runAfterBoth thenAcceptBothAsync thenCompletableFuture
runAfterEither acceptEither applyToEither
allOf
anyOf
|