本文快速回顾了常考的的知识点,用做面试复习,事半功倍。java
全复习手册文章导航git
点击公众号下方技术推文——面试冲刺程序员
已发布知识点复习手册github
Java基础知识点面试手册(上)面试
Java基础知识点面试手册(下)算法
Java容器(List、Set、Map)知识点快速复习手册(上)数据库
Java容器(List、Set、Map)知识点快速复习手册(中)segmentfault
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}
http://www.javashuo.com/article/p-gmlygbhe-mw.html
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方法太暴力了,不安全,因此被设置过期了。
http://www.javashuo.com/article/p-hwobvksy-nc.html
要注意的是: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包的实现示意图以下:
在这里插入图片描述
http://www.javashuo.com/article/p-gvvwqcdj-nc.html
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
若是文章对你有帮助,不妨收藏起来并转发给您的朋友们~