本文快速回顾了常考的的知识点,用作面试复习,事半功倍。
全复习手册文章导航
点击公众号下方技术推文——面试冲刺
已发布知识点复习手册
Java基础知识点面试手册(上)
Java基础知识点面试手册(下)
Java容器(List、Set、Map)知识点快速复习手册(上)
Java容器(List、Set、Map)知识点快速复习手册(中)
Java容器(List、Set、Map)知识点快速复习手册(下)
Redis基础知识点快速复习手册(上)
Redis基础知识点快速复习手册(下)
双非硕士的春招秋招经验总结——对校招,复习以及面试心态的理解
本文内容参考自CyC2018的Github仓库:CS-Notes
https://github.com/CyC2018/CS-Notes/
有删减,修改,补充额外增加内容
本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。
创建后尚未启动。
可能正在运行,也可能正在等待 CPU 时间片。
包含了操作系统线程状态中的 Running 和 Ready。
等待获取一个排它锁,如果其线程释放了锁就会结束此状态。
等待其它线程显式地唤醒,否则不会被分配 CPU 时间片。
无需等待其它线程显式地唤醒,在一定时间之后会被系统自动唤醒。
调用 Thread.sleep() 方法使线程进入限期等待状态时,常常用“使一个线程睡眠”进行描述。
调用 Object.wait() 方法使线程进入限期等待或者无限期等待时,常常用“挂起一个线程”进行描述。
睡眠和挂起是用来描述行为,而阻塞和等待用来描述状态。
阻塞和等待的区别在于,阻塞是被动的,它是在等待获取一个排它锁;
而等待是主动的,通过调用 Thread.sleep() 和 Object.wait() 等方法进入。
可以是线程结束任务之后自己结束,或者产生了异常而结束。
有三种使用线程的方法:
实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以说任务是通过线程驱动从而执行的。
需要实现 run() 方法。
通过 Thread 调用 start() 方法来启动线程。
1public class MyRunnable implements Runnable {
2 public void run() {
3 // ...
4 }
5}
1public static void main(String[] args) {
2 MyRunnable instance = new MyRunnable();
3 Thread thread = new Thread(instance);
4 thread.start();
5}
Callable就是Runnable的扩展。
与 Runnable 相比,Callable 可以有返回值,返回值通过 FutureTask 进行封装。
1public class MyCallable implements Callable<Integer> {
2 public Integer call() {
3 return 123;
4 }
5}
1public static void main(String[] args) throws ExecutionException, InterruptedException {
2 MyCallable mc = new MyCallable();
3 FutureTask<Integer> ft = new FutureTask<>(mc);
4 Thread thread = new Thread(ft);
5 thread.start();
6 System.out.println(ft.get());
7}
同样也是需要实现 run() 方法,并且最后也是调用 start() 方法来启动线程。
1public class MyThread extends Thread {
2 public void run() {
3 // ...
4 }
5}
1public static void main(String[] args) {
2 MyThread mt = new MyThread();
3 mt.start();
4}
严格说不能算方法,只能算实现方式:
实现接口会更好一些,因为:
详细解释:https://blog.csdn.net/lai_li/article/details/53070141?locationNum=13&fps=1
start方法:
通过该方法启动线程的同时也创建了一个线程,真正实现了多线程。无需等待run()方法中的代码执行完毕,就可以接着执行下面的代码。
run方法:
1package cn.thread.test;
2
3/*
4 * 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
5 */
6public class ThreadTest1 {
7
8 private int j;
9
10 public static void main(String[] args) {
11 ThreadTest1 tt = new ThreadTest1();
12 Inc inc = tt.new Inc();
13 Dec dec = tt.new Dec();
14
15
16 Thread t1 = new Thread(inc);
17 Thread t2 = new Thread(dec);
18 Thread t3 = new Thread(inc);
19 Thread t4 = new Thread(dec);
20 t1.start();
21 t2.start();
22 t3.start();
23 t4.start();
24
25 }
26
27 private synchronized void inc() {
28 j++;
29 System.out.println(Thread.currentThread().getName()+"inc:"+j);
30 }
31
32 private synchronized void dec() {
33 j--;
34 System.out.println(Thread.currentThread().getName()+"dec:"+j);
35 }
36
37 class Inc implements Runnable {
38 @Override
39 public void run() {
40 for (int i = 0; i < 100; i++) {
41 inc();
42 }
43 }
44 }
45
46 class Dec extends Thread {
47 @Override
48 public void run() {
49 for (int i = 0; i < 100; i++) {
50 dec();
51 }
52 }
53 }
54}
https://segmentfault.com/a/1190000014741369#articleHeader3
Executor 管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。异步是指多个任务的执行互不干扰,不需要进行同步操作。
当前线程池大小 :表示线程池中实际工作者线程的数量;
最大线程池大小 (maxinumPoolSize):表示线程池中允许存在的工作者线程的数量上限;
如果运行的线程少于 corePoolSize,则 Executor 始终首选添加新的线程,而不进行排队;
如果运行的线程等于或者多于 corePoolSize,则 Executor 始终首选将请求加入队列,而不是添加新线程;
如果无法将请求加入队列,即队列已经满了,则创建新的线程,除非创建此线程超出 maxinumPoolSize, 在这种情况下,任务将被拒绝。
实现了Executor接口,是用的最多的线程池,下面是已经默认实现的三种:
非常有弹性的线程池,对于新的任务,如果此时线程池里没有空闲线程,线程池会毫不犹豫的创建一条新的线程去处理这个任务。
1public static void main(String[] args) {
2 ExecutorService executorService = Executors.newCachedThreadPool();
3 for (int i = 0; i < 5; i++) {
4 executorService.execute(new MyRunnable());
5 }
6 executorService.shutdown();
7}
一个固定线程数的线程池,它将返回一个corePoolSize和maximumPoolSize相等的线程池。
相当于提供了延迟和周期执行功能的ThreadPoolExecutor类
守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。
当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程。
main() 属于非守护线程,垃圾回收是守护线程。
使用 setDaemon() 方法将一个线程设置为守护线程。
1public static void main(String[] args) {
2 Thread thread = new Thread(new MyRunnable());
3 thread.setDaemon(true);
4}
Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒。
sleep() 可能会抛出 InterruptedException,因为异常不能跨线程传播回 main() 中,因此必须在本地进行处理。线程中抛出的其它异常也同样需要在本地进行处理。
1public void run() {
2 try {
3 Thread.sleep(3000);
4 } catch (InterruptedException e) {
5 e.printStackTrace();
6 }
7}
对静态方法 Thread.yield() 的调用声明了当前线程已经完成了生命周期中最重要的部分,可以切换给其它线程来执行。该方法只是对线程调度器的一个建议,而且也只是建议具有相同优先级的其它线程可以运行。
1public void run() {
2 Thread.yield();
3}
一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。
现在已经没有强制线程终止的方法了!。
Stop方法太暴力了,不安全,所以被设置过时了。
https://segmentfault.com/a/1190000014463417#articleHeader9
要注意的是:interrupt不会真正停止一个线程,它仅仅是给这个线程发了一个信号告诉它,它应该要结束了(明白这一点非常重要!)
调用interrupt()并不是要真正终止掉当前线程,仅仅是设置了一个中断标志。这个中断标志可以给我们用来判断什么时候该干什么活!什么时候中断由我们自己来决定,这样就可以安全地终止线程了!
通过调用一个线程的 interrupt() 来中断该线程,可以中断处于:
那么就会抛出 InterruptedException,从而提前结束该线程。
但是不能中断 I/O 阻塞和 synchronized 锁阻塞。
对于以下代码,在 main() 中启动一个线程之后再中断它,由于线程中调用了 Thread.sleep() 方法,因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。
1public class InterruptExample {
2
3 private static class MyThread1 extends Thread {
4 @Override
5 public void run() {
6 try {
7 Thread.sleep(2000);
8 System.out.println("Thread run");
9 } catch (InterruptedException e) {
10 e.printStackTrace();
11 }
12 }
13 }
14}
1public static void main(String[] args) throws InterruptedException {
2 Thread thread1 = new MyThread1();
3 thread1.start();
4 thread1.interrupt();
5 System.out.println("Main run");
6}
1Main run
2java.lang.InterruptedException: sleep interrupted
3 at java.lang.Thread.sleep(Native Method)
4 at InterruptExample.lambda$main$0(InterruptExample.java:5)
5 at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
6 at java.lang.Thread.run(Thread.java:745)
interrupt线程中断还有另外两个方法(检查该线程是否被中断):
如果一个线程的 run() 方法执行一个无限循环(不属于阻塞、限期等待、非限期等待),例如while(True),并且没有执行 sleep() 等会抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束。
然而,
但是调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程。
1Thread t1 = new Thread( new Runnable(){
2 public void run(){
3 // 若未发生中断,就正常执行任务
4 while(!Thread.currentThread.isInterrupted()){
5 // 正常任务代码……
6 }
7 // 中断的处理代码……
8 doSomething();
9 }
10} ).start();
以下使用 Lambda 创建线程,相当于创建了一个匿名内部线程。
1public static void main(String[] args) {
2 ExecutorService executorService = Executors.newCachedThreadPool();
3 executorService.execute(() -> {
4 try {
5 Thread.sleep(2000);
6 System.out.println("Thread run");
7 } catch (InterruptedException e) {
8 e.printStackTrace();
9 }
10 });
11 executorService.shutdownNow();
12 System.out.println("Main run");
13}
1Main run
2java.lang.InterruptedException: sleep interrupted
3 at java.lang.Thread.sleep(Native Method)
4 at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
5 at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
6 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
7 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
8 at java.lang.Thread.run(Thread.java:745)
如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future 对象,通过调用该对象的 cancel(true) 方法就可以中断线程。
1Future<?> future = executorService.submit(() -> {
2 // ..
3});
4future.cancel(true);
https://blog.csdn.net/u012545728/article/details/80843595
所谓不可重入锁,即若当前线程执行某个方法已经获取了该锁,那么在方法中尝试再次获取锁时,就会获取不到被阻塞。
1public class Count{
2 Lock lock = new Lock();
3 public void print(){
4 lock.lock();
5 doAdd();
6 lock.unlock();
7 }
8 public void doAdd(){
9 lock.lock();
10 //do something
11 lock.unlock();
12 }
13}
所谓可重入,意味着线程可以进入它已经拥有的锁的同步代码块儿
我们设计两个线程调用print()方法,第一个线程调用print()方法获取锁,进入lock()方法,由于初始lockedBy是null,所以不会进入while而挂起当前线程,而是是增量lockedCount并记录lockBy为第一个线程。接着第一个线程进入doAdd()方法,由于同一进程,所以不会进入while而挂起,接着增量lockedCount,当第二个线程尝试lock,由于isLocked=true,所以他不会获取该锁,直到第一个线程调用两次unlock()将lockCount递减为0,才将标记为isLocked设置为false。
可重入锁的概念和设计思想大体如此,Java中的可重入锁ReentrantLock设计思路也是这样
synchronized和ReentrantLock都是可重入锁
1public void func () {
2 synchronized (this) {
3 // ...
4 }
5}
它只作用于同一个对象,如果调用两个不同对象上的同步代码块,就不会进行同步。
1public synchronized void func () {
2 // ...
3}
它和同步代码块一样,只作用于同一个对象。
1public void func() {
2 synchronized (SynchronizedExample.class) {
3 // ...
4 }
5}
作用于整个类,也就是说两个线程调用同一个类的不同对象上的这种同步语句,也需要进行同步。
1public synchronized static void fun() {
2 // ...
3}
作用于整个类。
当方法(代码块)执行完毕后会自动释放锁,不需要做任何的操作。
有ReentrantLock和ReentrantReadWriteLock,后者分为读锁和写锁,读锁允许并发访问共享资源。
1public class LockExample {
2
3 private Lock lock = new ReentrantLock();
4
5 public void func() {
6 lock.lock();
7 try {
8 for (int i = 0; i < 10; i++) {
9 System.out.print(i + " ");
10 }
11 } finally {
12 lock.unlock(); // 确保释放锁,从而避免发生死锁。
13 }
14 }
15}
1public static void main(String[] args) {
2 LockExample lockExample = new LockExample();
3 ExecutorService executorService = Executors.newCachedThreadPool();
4 executorService.execute(() -> lockExample.func());
5 executorService.execute(() -> lockExample.func());
6}
10 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
ReentrantLock 是 java.util.concurrent(J.U.C)包中的锁,相比于 synchronized,它多了以下高级功能:
当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待,改为处理其他事情,可中断特性对处理执行时间非常长的同步块很有帮助。
公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁;而非公平锁则不保证这一点,在锁被释放时,任何一个等待锁的线程都有机会获得锁。
ReentrantLock 默认情况下也是非公平的,但可以通过带布尔值的构造函数要求使用公平锁。
我们知道synchronized内置锁和ReentrantLock都是互斥锁(一次只能有一个线程进入到临界区(被锁定的区域)
ReentrantReadWriteLock优点:
synchronized 是 JVM 实现的,而 ReentrantLock 是 JDK 实现的。
新版本 Java 对 synchronized 进行了很多优化,例如自旋锁等,synchronized 与 ReentrantLock 大致相同。
ReentrantLock 可中断,而 synchronized 不行。
一个 ReentrantLock 可以同时绑定多个 Condition 对象。
除非需要使用 ReentrantLock 的高级功能,否则优先使用 synchronized。
当多个线程可以一起工作去解决某个问题时,如果某些部分必须在其它部分之前完成,那么就需要对线程进行协调。
在线程中调用另一个线程的 join() 方法,会将当前线程挂起,而不是忙等待, 直到目标线程结束。
对于以下代码,虽然 b 线程先启动,但是因为在 b 线程中调用了 a 线程的 join() 方法,因此 b 线程会等待 a 线程结束才继续执行,因此最后能够保证 a 线程的输出先与 b 线程的输出。
调用 wait() 使得线程等待某个条件满足,线程在等待时会被挂起,当其他线程的运行使得这个条件满足时,其它线程会调用 notify() 或者 notifyAll() 来唤醒挂起的线程。
它们都属于 Object 的一部分,而不属于 Thread。
只能用在同步方法或者同步控制块中使用,否则会在运行时抛出 IllegalMonitorStateExeception。
使用 wait() 挂起期间,线程会释放锁。这是因为,如果没有释放锁,那么其它线程就无法进入对象的同步方法或者同步控制块中,那么就无法执行 notify() 或者 notifyAll() 来唤醒挂起的线程,造成死锁。
wait() 和 sleep() 的区别
java.util.concurrent 类库中提供了 Condition 类来实现线程之间的协调,可以在 Condition 上调用 await() 方法使线程等待,其它线程调用 signal() 或 signalAll() 方法唤醒等待的线程。
相比于 wait() 这种等待方式,await() 可以指定等待的条件,因此更加灵活。
使用 Lock 来获取一个 Condition 对象。
1public class AwaitSignalExample {
2 private Lock lock = new ReentrantLock();
3 private Condition condition = lock.newCondition();
4
5 public void before() {
6 lock.lock();
7 try {
8 System.out.println("before");
9 condition.signalAll();
10 } finally {
11 lock.unlock();
12 }
13 }
14
15 public void after() {
16 lock.lock();
17 try {
18 condition.await();
19 System.out.println("after");
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 } finally {
23 lock.unlock();
24 }
25 }
26}
1public static void main(String[] args) {
2 ExecutorService executorService = Executors.newCachedThreadPool();
3 AwaitSignalExample example = new AwaitSignalExample();
4 executorService.execute(() -> example.after());
5 executorService.execute(() -> example.before());
6}
1before
2after
从整体来看,concurrent包的实现示意图如下:
在这里插入图片描述
https://segmentfault.com/a/1190000014595928
java.util.concurrent(J.U.C)大大提高了并发性能,AQS 被认为是 J.U.C 的核心。
AbstractQueuedSynchronizer简称为AQS:AQS定义了一套多线程访问共享资源的同步器框架,许多同步类实现都依赖于它,我们Lock之类的两个常见的锁都是基于它来实现的。
维护了一个计数器 cnt,每次调用 countDown() 方法会让计数器的值减 1,减到 0 的时候,那些因为调用 await() 方法而在等待的线程就会被唤醒。
使用说明:
1public class CountdownLatchExample {
2 public static void main(String[] args) throws InterruptedException {
3 final int totalThread = 10;
4 CountDownLatch countDownLatch = new CountDownLatch(totalThread);
5 ExecutorService executorService = Executors.newCachedThreadPool();
6 for (int i = 0; i < totalThread; i++) {
7 executorService.execute(() -> {
8 System.out.print("run..");
9 countDownLatch.countDown();
10 });
11 }
12 countDownLatch.await();
13 System.out.println("end");
14 executorService.shutdown();
15 }
16}
17
18run..run..run..run..run..run..run..run..run..run..end
CyclicBarrier 的字面意思是可循环使用(Cyclic)的屏障(Barrier)。它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所有被屏障拦截的线程才会继续干活。
和 CountdownLatch相似,都是通过维护计数器来实现的。但是它的计数器是递增的,每次执行 await() 方法之后,计数器会加 1,直到计数器的值和设置的值相等,等待的所有线程才会继续执行。
CyclicBarrier可以被重用(对比于CountDownLatch是不能重用的),CyclicBarrier 的计数器通过调用 reset() 方法可以循环使用,所以它才叫做循环屏障。
在这里插入图片描述
1public CyclicBarrier(int parties, Runnable barrierAction) {
2 if (parties <= 0) throw new IllegalArgumentException();
3 this.parties = parties;
4 this.count = parties;
5 this.barrierCommand = barrierAction;
6}
7
8public CyclicBarrier(int parties) {
9 this(parties, null);
10}
1public class CyclicBarrierExample {
2 public static void main(String[] args) {
3 final int totalThread = 10;
4 CyclicBarrier cyclicBarrier = new CyclicBarrier(totalThread);
5 ExecutorService executorService = Executors.newCachedThreadPool();
6 for (int i = 0; i < totalThread; i++) {
7 executorService.execute(() -> {
8 System.out.print("before..");
9 try {
10 cyclicBarrier.await();
11 } catch (InterruptedException | BrokenBarrierException e) {
12 e.printStackTrace();
13 }
14 System.out.print("after..");
15 });
16 }
17 executorService.shutdown();
18 }
19}
20before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..after..
Semaphore 就是操作系统中的信号量,可以控制对互斥资源的访问线程数。
1public class SemaphoreExample {
2 public static void main(String[] args) {
3 final int clientCount = 3;
4 final int totalRequestCount = 10;
5 Semaphore semaphore = new Semaphore(clientCount);
6 ExecutorService executorService = Executors.newCachedThreadPool();
7 for (int i = 0; i < totalRequestCount; i++) {
8 executorService.execute(()->{
9 try {
10 semaphore.acquire();
11 System.out.print(semaphore.availablePermits() + " ");
12 } catch (InterruptedException e) {
13 e.printStackTrace();
14 } finally {
15 semaphore.release();
16 }
17 });
18 }
19 executorService.shutdown();
20 }
21}
在介绍 Callable 时我们知道它可以有返回值,返回值通过 Future进行封装。
FutureTask 实现了 RunnableFuture 接口,该接口继承自 Runnable 和 Future接口,这使得 FutureTask 既可以当做一个任务执行,也可以有返回值。
1public class FutureTask<V> implements RunnableFuture<V>
2
1public interface RunnableFuture<V> extends Runnable, Future<V>
2
当一个计算任务需要执行很长时间,那么就可以用 FutureTask 来封装这个任务,用一个线程去执行该任务,然后其它线程继续执行其它任务。当需要该任务的计算结果时,再通过 FutureTask 的 get() 方法获取。
1public class FutureTaskExample {
2 public static void main(String[] args) throws ExecutionException, InterruptedException {
3 FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
4 @Override
5 public Integer call() throws Exception {
6 int result = 0;
7 for (int i = 0; i < 100; i++) {
8 Thread.sleep(10);
9 result += i;
10 }
11 return result;
12 }
13 });
14
15 Thread computeThread = new Thread(futureTask);
16 computeThread.start();
17
18 Thread otherThread = new Thread(() -> {
19 System.out.println("other task is running...");
20 try {
21 Thread.sleep(1000);
22 } catch (InterruptedException e) {
23 e.printStackTrace();
24 }
25 });
26 otherThread.start();
27 System.out.println(futureTask.get());
28 }
29}
1other task is running...
24950
java.util.concurrent.BlockingQueue 接口有以下阻塞队列的实现:
使用 BlockingQueue 实现生产者消费者问题
1public class ProducerConsumer {
2
3 private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
4
5 private static class Producer extends Thread {
6 @Override
7 public void run() {
8 try {
9 queue.put("product");
10 } catch (InterruptedException e) {
11 e.printStackTrace();
12 }
13 System.out.print("produce..");
14 }
15 }
16
17 private static class Consumer extends Thread {
18
19 @Override
20 public void run() {
21 try {
22 String product = queue.take();
23 } catch (InterruptedException e) {
24 e.printStackTrace();
25 }
26 System.out.print("consume..");
27 }
28 }
29}
1public static void main(String[] args) {
2 for (int i = 0; i < 2; i++) {
3 Producer producer = new Producer();
4 producer.start();
5 }
6 for (int i = 0; i < 5; i++) {
7 Consumer consumer = new Consumer();
8 consumer.start();
9 }
10 for (int i = 0; i < 3; i++) {
11 Producer producer = new Producer();
12 producer.start();
13 }
14}
1produce..produce..consume..consume..produce..consume..produce..consume..produce..consume..
都是线程安全的,不然叫什么并发类呢
ArrayBlockingQueue, LinkedBlockingQueue 继承自 BlockingQueue, 他们的特点就是 Blocking, Blocking 特有的方法就是 take() 和 put(), 这两个方法是阻塞方法, 每当队列容量满的时候, put() 方法就会进入wait, 直到队列空出来, 而每当队列为空时, take() 就会进入等待, 直到队列有元素可以 take()
ArrayBlockingQueue, LinkedBlockingQueue 区别在于:
链表和数组性质决定的
ConcurrentLinkedQueue 通过 CAS 操作实现了无锁的 poll() 和 offer(),
他的容量是动态的,
由于无锁, 所以在 poll() 或者 offer() 的时候 head 与 tail 可能会改变,所以它会持续的判断 head 与 tail 是否改变来保证操作正确性, 如果改变, 则会重新选择 head 与 tail.
除了ScheduledThreadPoolExecutor和ThreadPoolExecutor类线程池以外,还有一个是JDK1.7新增的线程池:ForkJoinPool线程池
主要用于并行计算中,和 MapReduce 原理类似,都是把大的计算任务拆分成多个小任务并行计算。
1public class ForkJoinExample extends RecursiveTask<Integer> {
2 private final int threhold = 5;
3 private int first;
4 private int last;
5
6 public ForkJoinExample(int first, int last) {
7 this.first = first;
8 this.last = last;
9 }
10
11 @Override
12 protected Integer compute() {
13 int result = 0;
14 if (last - first <= threhold) {
15 // 任务足够小则直接计算
16 for (int i = first; i <= last; i++) {
17 result += i;
18 }
19 } else {
20 // 拆分成小任务
21 int middle = first + (last - first) / 2;
22 ForkJoinExample leftTask = new ForkJoinExample(first, middle);
23 ForkJoinExample rightTask = new ForkJoinExample(middle + 1, last);
24 leftTask.fork();
25 rightTask.fork();
26 result = leftTask.join() + rightTask.join();
27 }
28 return result;
29 }
30}
1public static void main(String[] args) throws ExecutionException, InterruptedException {
2 ForkJoinExample example = new ForkJoinExample(1, 10000);
3 ForkJoinPool forkJoinPool = new ForkJoinPool();
4 Future result = forkJoinPool.submit(example);
5 System.out.println(result.get());
6}
ForkJoin 使用 ForkJoinPool 来启动,它是一个特殊的线程池,线程数量取决于 CPU 核数。
1public class ForkJoinPool extends AbstractExecutorService
2
ForkJoinPool 实现了工作窃取算法来提高 CPU 的利用率。每个线程都维护了一个双端队列,用来存储需要执行的任务。工作窃取算法允许空闲的线程从其它线程的双端队列中窃取一个任务来执行。窃取的任务必须是最晚的任务,避免和队列所属线程发生竞争。例如下图中,Thread2 从 Thread1 的队列中拿出最晚的 Task1 任务,Thread1 会拿出 Task2 来执行,这样就避免发生竞争。但是如果队列中只有一个任务时还是会发生竞争。
在这里插入图片描述
我是蛮三刀把刀,目前为后台开发工程师。主要关注后台开发,网络安全,Python爬虫等技术。
来微信和我聊聊:yangzd1102
Github:https://github.com/qqxx6661
拥有专栏:Leetcode题解(Java/Python)、Python爬虫开发
https://www.zhihu.com/people/yang-zhen-dong-1/
拥有专栏:码农面试助攻手册
https://juejin.im/user/5b48015ce51d45191462ba55
https://www.jianshu.com/u/b5f225ca2376
个人公众号:Rude3Knife
如果文章对你有帮助,不妨收藏起来并转发给您的朋友们~
原文:https://blog.51cto.com/15047490/2561270