1.JUC
JUC就是java.util .concurrent工具包的简称。这是一个处理线程的工具包,JDK 1.5开始出现的。
2.线程和进程
进程是操作系统分配资源的单位,线程是调度的基本单位,线程之间共享进程资源。
一个进程往往包含多个进程,至少包含一个
java默认包含2个线程,main和GC
java不可以自己开启线程,只能通过本地方法调用c来执行
对于java来说,线程就是一个单独的的资源类,没有任何附属的操作,只有属性和方法
并行和并发
并发(多线程操作同一个资源)
- CPU一核或者少于线程数量,模拟出多条线程,不断的上下文切换
并发(多个人一起走)
- 多核,多线程可以同时执行
并发编程的本质:充分利用CPU的资源
线程有多少种状态
1.新创建 new
2.运行时 runnable
3.阻塞 blocked
4.等待 waiting(一直等待)
5.超时等待 timed_waiting(过时就不等待)
6.终止 Terminated
wait和sleep区别
1.来自不同类
- wait=>Object
- sleep=>Thread
2.关于锁的释放
- wait:会释放锁
- sleep:不会释放锁
3.使用范围
- wait:必须在同步代码块,同步方法中
- sleep:可以在任何地方
4.捕获异常
- wait:不需要捕获异常
- sleep:需要捕获异常
3.Lock锁(重点)
传统synchronized
synchronized本质就是队列、锁
@Test
void test1(){
Ticket ticket = new Ticket();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"A").start();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"B").start();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"C").start();
}
}
class Ticket{
private int num=30;
public synchronized void sale() {
//业务代码
if (num>0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(num--)+"票,剩余:"+num);
}
}
}
Lock接口
加锁:lock();
解锁:unlock();
Lock接口有三个实现类
- 可重入锁 ReetrantLock()
- 读锁 ReentrantReadWriteLock.ReadLock()
- 写锁 ReentrantReadWriteLock.WriteLock()
可重入锁又分为两种
- 公平锁:十分公平,先来后到
- 非公平锁:十分不公平,可以插队(默认)
@Test
void test1(){
Ticket ticket = new Ticket();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"A").start();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"B").start();
new Thread(()->{ for (int i = 1; i < 40; i++) ticket.sale(); },"C").start();
}
}
class Ticket{
private int num=30;
Lock lock=new ReentrantLock();
public void sale() {
lock.lock(); //加锁
try {
//业务代码
if (num>0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(num--)+"票,剩余:"+num);
}
} catch (Exception exception) {
exception.printStackTrace();
}finally {
lock.unlock();//解锁
}
}
}
Synchronized和Lock的区别
1.Synchronized是内置的关键字;Lock是类
2.Synchronized使用在少量代码同步问题;Lock使用在大量代码同步问题
3.Synchronized 可重入锁,不可中断,非公平的;Lock 可重入锁 可中断lockInterruptibly()
可以是非公平锁也可以是公平锁
4.Synchronized 线程A获得锁,线程B等待;线程A阻塞,线程B一直等待;Lock可以使用tryLock()获取锁,不同一定等待下去
5.Synchronized无法获取锁的状态,Lock可以判断是否获取到了锁
6.Synchronized是自动获取锁的和释放锁;Lock是手动获取锁并必须手动释放锁,不然会出现死锁
4.生产者和消费者问题
线程之间的通信问题:生产者和消费者
面试:单例模式、排序算法、生产者和消费者
生产者和消费者问题 synchronized版
/**
* 线程之间的通信问题:生产者和消费者 等待唤醒 通知唤醒
*/
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
}
}
class Data{
private int num=0;
public synchronized void increment() throws InterruptedException {
if (num!=0){
//等待
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//通知其他线程 +1完毕
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
if (num==0){
//等待
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//通知其他线程 -1完毕
this.notifyAll();
}
}
问题存在,A,B,C,D四个线程!会引起虚假唤醒
解决方案 if改为 while
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
class Data{
private int num=0;
public synchronized void increment() throws InterruptedException {
while (num!=0){
//等待
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//通知其他线程 +1完毕
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
while (num==0){
//等待
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//通知其他线程 -1完毕
this.notifyAll();
}
}
JUC的生产者和消费者问题
public class A {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
class Data{
private int num=0;
Lock lock=new ReentrantLock();
Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
lock.lock();
try {
//业务代码
while (num!=0){
//等待
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//唤醒
condition.signalAll();
} catch (Exception exception) {
exception.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException {
lock.lock();
try {
while (num==0){
//等待
condition.await();
}
num--;
System.out.println(Thread.currentThread().getName()+"=>"+num);
//通知其他线程 -1完毕
condition.signalAll();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
lock.unlock();
}
}
}
Condition可以精准的通知和唤醒线程
public class C {
public static void main(String[] args) {
Data3 data = new Data3();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printA();
}},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printB();
}},"B").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
data.printC();
}},"C").start();
}
}
class Data3{
Lock lock=new ReentrantLock();
Condition condition1=lock.newCondition();
Condition condition2=lock.newCondition();
Condition condition3=lock.newCondition();
private int num=1;
public void printA(){
lock.lock();
try {
//业务 判断 执行 通知
while (num!=1){
condition1.await();
}
System.out.println(Thread.currentThread().getName()+"=>AAAAAA");
num=2;
//唤醒B
condition2.signal();
} catch (Exception exception) {
exception.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB(){
lock.lock();
try {
while (num!=2){
condition2.await();
}
System.out.println(Thread.currentThread().getName()+"=>BBBBBB");
num=3;
//唤醒C
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC(){
lock.lock();
try {
while (num!=3){
condition3.await();
}
System.out.println(Thread.currentThread().getName()+"=>CCCCCCC");
num=1;
//唤醒C
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
5.锁
如何判断锁是谁的!永远知道什么锁,锁到底锁什么
锁对象和Class
class Phone{
//Synchronized锁的对象是这个方法的调用者
//两个方法同时用的是一把锁,谁先拿到谁执行
public synchronized void sendSms(){
System.out.println("sndSms");
}
public synchronized void call(){
System.out.println("call");
}
}
static 修饰时候是锁Class,Class模板只有一个
new一个实例的时候是锁一个具体实例
6.集合类不安全
List不安全
/**
* java.util.ConcurrentModificationException 并发修改异常
*/
public class ListTest {
public static void main(String[] args) {
/**
* 并发下ArrayList不安全
*
* 解决方案:
* 1. List<String> list=new Vector<>();
* 2. List<String> list= Collections.synchronizedList(new ArrayList<>());
* 3. List<String> list= new CopyOnWriteArrayList<>();
*/
/**
* CopyOrWriteArrayList写入时复制 COW 计算机程序设计领域的一个优化策略
* 多个线程调用的时候。读的时候不会上锁,不会阻塞,看的还是原来数据,当有线程要修改数据的时候就会复制一个新的副本,在副本中进行操作,更改完后替换原来的数据
* 是为了在写入的时候避免造成数据上覆盖的问题
* 读写分离
*
* CopyOrWriteArrayList 比 Vector好在哪?
*
* CopyOrWriteArrayList 底层使用的是lock锁
* Vector使用的是Synchronized锁,效率低下
*/
List<String> list= new CopyOnWriteArrayList<>();
List<String> list1= Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
/**
* 并发下ArrayList不安全
*
* 解决方案:
* 1. List<String> list=new Vector<>();
* 2. List<String> list= Collections.synchronizedList(new ArrayList<>());
* 3. List<String> list= new CopyOnWriteArrayList<>();
*/
/**
* CopyOrWriteArrayList写入时复制 COW 计算机程序设计领域的一个优化策略
* 多个线程调用的时候。读的时候不会上锁,不会阻塞,看的还是原来数据,当有线程要修改数据的时候就会复制一个新的副本,在副本中进行操作,更改完后替换原来的数据
* 是为了在写入的时候避免造成数据上覆盖的问题
* 读写分离
*
* CopyOrWriteArrayList 比 Vector好在哪?
*
* CopyOrWriteArrayList 底层使用的是lock锁
* Vector使用的是Synchronized锁,效率低下
*/
Set不安全
/**
* 同理可证 java.util.ConcurrentModificationException
*
* 解决方案
* 1.Set<String> set = Collections.synchronizedSet(new HashSet<>());
* 2.Set<String> set =new CopyOnWriteArraySet<>();
*/
public class SetTest {
public static void main(String[] args) {
Set<String> set =new CopyOnWriteArraySet<>();
for (int i = 0; i < 30; i++) {
new Thread(()->{
set.add((UUID.randomUUID().toString().substring(0,5)));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
hashSet底层原理
Map不安全
/**
*
* 同理可证 java.util.ConcurrentModificationException
*
* hashmap默认等价于new HashMap(16,0.75)
*解决方案
* 1. Map<String,String> map =new ConcurrentHashMap<>();
* 2. Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
*/
public class MapTest {
public static void main(String[] args) {
Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
for (int i = 0; i < 30; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
7.Callable
1.可以有返回值
2.可以抛出异常
3.方法不同,run()/call()
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// new Thread(new Runnable()).start();
//new Thread(new FutureTask<V>()).start();
//new Thread(new FutureTask<V>(Callable)).start();
MyThread myThread=new MyThread();
FutureTask<Integer> task = new FutureTask<>(myThread);//适配类
new Thread(task,"A").start();
new Thread(task,"B").start();//结果会被缓存
Integer integer = task.get();//获取返回结果 这个方法可能会产生阻塞,所以一般放在最后或者使用异步通信
System.out.println(integer);
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int num=1;
System.out.println(num+"==>");
return num;
}
}
细节:
1.有缓存
2.结果可能需要等待,会阻塞
8.常用辅助类(必会)
8.1 CountDownLatch
减法计数器
//减法计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//必须要执行任务的时候,再使用
CountDownLatch countDownLatch = new CountDownLatch(6);//数量为6
for (int i = 1; i <=6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"out");
countDownLatch.countDown();//数量减1
},String.valueOf(i)).start();
}
countDownLatch.await();//等待计数器为0,才继续向下执行
System.out.println("close door");
}
}
原理:countDownLatch.countDown();//数量减1countDownLatch.await();//等待计数器为0,才继续向下执行
每次有线程调用countDownLatch.countDown()数量减1,假设计数器变为0, countDownLatch.await();就会被唤醒继续向下执行
8.2 CyclicBarrier
加法计数器
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功");});
for (int i = 1; i <=7; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"龙珠召唤");
try {
cyclicBarrier.await();//等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
8.3 Semaphore信号量
public class SemaphoreDemo { public static void main(String[] args) { //线程数量:停车位 限流有秩序 Semaphore semaphore = new Semaphore(3); for (int i = 1; i <=6 ; i++) { new Thread(()->{ try { semaphore.acquire();//得到 System.out.println(Thread.currentThread().getName()+"抢到了车位"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName()+"离开车位"); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release();//释放 } },String.valueOf(i)).start(); } } }
原理:semaphore.acquire(); 获得,如果已经满了信号量-1,等待,等待给释放semaphore.release();释放,会将当前的信号量+1,然后唤醒等待的线程
作用:多个共享资源互斥使用!并发限流,控制最大的线程数
9.读写锁
ReadWriteLock
/** * 独占锁(写锁) 一次只能被一个线程占有 * 共享锁(读锁) 多线程可以同时占有 * ReadWriteLock * 读-读 可以共存 * 读-写 不能共存 * 写-写 不能共存 */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCacheLock myCache = new MyCacheLock(); for (int i = 1; i <10 ; i++) { final int temp=i; new Thread(()->{ myCache.put(temp+"",temp+""); },String.valueOf(i)).start(); } for (int i = 1; i <10 ; i++) { final int temp=i; new Thread(()->{ myCache.get(temp+""); },String.valueOf(i)).start(); } } } class MyCache{ private volatile Map<String,Object> map=new HashMap<>(); //存、写 public void put(String key,Object value){ System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入OK"); } //读 public void get(String key){ System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取OK"); } } class MyCacheLock{ private volatile Map<String,Object> map=new HashMap<>(); private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock(); //存、写 public void put(String key,Object value){ readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"写入"+key); map.put(key,value); System.out.println(Thread.currentThread().getName()+"写入OK"); } catch (Exception e){ e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } //读 public void get(String key){ readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"读取"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取OK"); } catch (Exception exception) { exception.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } }
10.阻塞队列
BlockingQueue
什么情况下会使用到阻塞队列
1.多线程并发情况
2.线程池
| 方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞 等待 | 超时等待 |
|---|---|---|---|---|
| 添加 | add | offer | put | offer( ,,) |
| 移除 | remove | poll | take | poll( ,) |
| 判断队首元素 | element | peek | – | – |

/** * 抛出异常 */ public static void test1(){ //队列大小 ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3); blockingQueue.add("a"); blockingQueue.add("b"); blockingQueue.add("c"); //Exception in thread "main" java.lang.IllegalStateException: Queue full // blockingQueue.add("d"); blockingQueue.remove(); blockingQueue.remove(); blockingQueue.remove(); // java.util.NoSuchElementException // blockingQueue.remove(); }
/** * 有返回值,不抛出异常 */ public static void test2(){ ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.offer("a")); System.out.println(blockingQueue.offer("b")); System.out.println(blockingQueue.offer("c")); System.out.println(blockingQueue.offer("d"));//不抛出异常 返回false System.out.println("=============="); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll());//不抛出异常 返回null }
/** * 等待 阻塞 一直阻塞 */ public static void test3() throws InterruptedException { ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); //一直阻塞 blockingQueue.put("a"); blockingQueue.put("b"); blockingQueue.put("c"); blockingQueue.put("d");//一直等待阻塞 blockingQueue.take(); blockingQueue.take(); blockingQueue.take(); blockingQueue.take();//一直阻塞 }
/** * 等待 阻塞 超时等待 */ public static void test4() throws InterruptedException { ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.offer("a")); System.out.println(blockingQueue.offer("b")); System.out.println(blockingQueue.offer("c")); System.out.println(blockingQueue.offer("d",2, TimeUnit.SECONDS));//等待超过2秒退出 System.out.println("=============="); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS));//等待超过2秒退出 }
SynchronousQueue同步队列
没有容量
进去一个元素,必须等待取出来之后,才能往里面放一个元素
put、take
/** * 同步列队 * 和其他的BlockQueue不一样,SynchronousQueue不存储元素 * put了一个元素,就必须take取出来,否则不能直接put进去 */ public class SynchronousQueueDemo { public static void main(String[] args) { SynchronousQueue<String> queue = new SynchronousQueue<>(); new Thread(()->{ try { queue.put("a"); queue.put("b"); queue.put("c"); } catch (InterruptedException e) { e.printStackTrace(); } },"T1").start(); new Thread(()->{ try { TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName()+"=>"+queue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName()+"=>"+queue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName()+"=>"+queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } },"T2").start(); } }
11.线程池(重点)
线程池:三大方法、7大参数、4种拒绝策略
池化技术
程序运行,本质:占用系统资源!优化资源使用=》池化技术
线程池,连接池,内存池,对象池…
池化技术:事先准备好资源,有人要用,就来这里拿,拿完归还
线程池的好处:
1.降低资源消耗
2.提高响应速度
3.方便管理
线程复用、可以控制最大并发数、管理线程
线程池:三大方法
/** * 使用线程池之后就用线程池来创建线程 */ public class Demo1 { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor();//单线程 ExecutorService threadPool1 = Executors.newFixedThreadPool(5);//创建一个固定大小的线程池 ExecutorService threadPool2 = Executors.newCachedThreadPool();//可伸缩,遇强则强,遇弱则弱 try { for (int i = 0; i < 100; i++) { threadPool2.execute(()->{ System.out.println(Thread.currentThread().getName()+" ok"); }); } } catch (Exception exception) { exception.printStackTrace(); } finally { //关闭线程池 threadPool2.shutdown(); } } }
7大参数
源码分析
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
本质使用:ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,//核心线程池大小 int maximumPoolSize,//最大核心线程池大小 long keepAliveTime,//超时了没有人调用就会释放 TimeUnit unit,//超时单位 BlockingQueue<Runnable> workQueue,//阻塞队列 ThreadFactory threadFactory,//创建线程工厂,一般不用动 RejectedExecutionHandler handler//拒绝策略) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
手动创建一个线程池
/** * Executors 工具类 * * new ThreadPoolExecutor.AbortPolicy()//人满了就拒绝进入,抛出异常 java.util.concurrent.RejectedExecutionException * new ThreadPoolExecutor.CallerRunsPolicy()//哪来的就回哪里 * new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,不会抛出异常 * new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常 */ public class Demo02 { public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常 ); try { //最大承载量:Deque+max //超过RejectedExecutionException for (int i = 0; i < 12; i++) { threadPoolExecutor.execute(()->{ System.out.println(Thread.currentThread().getName()+" ok"); }); } } catch (Exception exception) { exception.printStackTrace(); } finally { threadPoolExecutor.shutdown(); } } }
四种拒绝策略
new ThreadPoolExecutor.AbortPolicy()//人满了就拒绝进入,抛出异常 java.util.concurrent.RejectedExecutionException
new ThreadPoolExecutor.CallerRunsPolicy()//哪来的就回哪里
new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试去和最早的竞争,不会抛出异常
new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常
小结和拓展
最大线程如何去设置
了解:IO密集型,CPU密集型(调优)
/** * Executors 工具类 * * * 最大线程如何定义 * 1.CPU密集型 ,几核就是几,保持cpu效率最高 * 2.IO密集型 >判断你的程序中十分耗IO的线程 * 程序 n个大型任务 io十分占用资源 */ public class Demo02 { public static void main(String[] args) { //动态获取cpu核数 System.out.println(Runtime.getRuntime().availableProcessors()); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 2, Runtime.getRuntime().availableProcessors(), 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy()//队列满了,丢掉任务,不会抛出异常 ); try { //最大承载量:Deque+max //超过RejectedExecutionException for (int i = 0; i < 12; i++) { threadPoolExecutor.execute(()->{ System.out.println(Thread.currentThread().getName()+" ok"); }); } } catch (Exception exception) { exception.printStackTrace(); } finally { threadPoolExecutor.shutdown(); } } }
12.四大函数式接口(必须掌握)
新时代的程序员:lambda表达式,链式编程,函数式接口,Stream流式计算
函数式接口:只有一个抽象方法的接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//超级多FunctionInterface
//简化编程模型,在新版本的框架底层大量运用
//foreach(消费者类的函数式接口)
Function函数型接口
/** * Function函数式接口 有一个输入参数,有一个输出 * *只要是 函数型接口 可以用 Lambda表达式简化 */ public class Demo01 { public static void main(String[] args) { //工具类:输出输入的值 // Function function<String,String>=new Function<String,String>() { // @Override // public String apply(String s) { // return s; // } // }; Function<String,String> function=(str)->{return str;}; } }
Predicate断定型接口
/** * 断定型接口:有一个输入参数,返回值只能是布尔值 */ public class Demo2 { public static void main(String[] args) { //判断字符串知否为空 // Predicate<String> predicate=new Predicate<String>() { // @Override // public boolean test(String str) { // return str.isEmpty(); // } // }; //lambda表达式 Predicate<String> predicate=(str)->{ return str.isEmpty();}; } }
Consumer消费型接口
/** * Consumer消费型接口 :只有输出没有返回值 * */ public class Demo03 { public static void main(String[] args) { // Consumer<String> consumer=new Consumer<String>() { // @Override // public void accept(String str) { // System.out.println(str); // } // }; Consumer<String> consumer=(str)->{ System.out.println(str); }; } }
Supplier供给型接口
/** * Supplier供给型接口,没有参数,只有返回值 */ public class Demo04 { public static void main(String[] args) { // Supplier<String> supplier=new Supplier<String>() { // @Override // public String get() { // return "123"; // } // }; Supplier<String> supplier=()->{return "123";}; } }
13.Stream流式计算
什么是Stream流式计算
大数据:存储+计算
集合、MySQL本质就是存储东西的
计算都应该交给流来操作
public class Test { public static void main(String[] args) { User user1 = new User(1, "a", 23); User user2 = new User(2, "b", 24); User user3 = new User(3, "c", 25); //集合就是存储 List<User> list = Arrays.asList(user1, user2, user3); //计算交给流 //链式编程 list.stream() .filter(user -> {return user.getId()%2==0;}) .map(user -> {return user.getName().toUpperCase();}) .sorted((u1,u2)->{return u1.compareTo(u2);}) .limit(1) .forEach(System.out::println); } }
ForkJoin 分支合并
什么是ForkJoin
ForkJoin在jdk1.7,并行执行任务!提高效率,大数据量!
大数据:Map Reduce(把大任务拆分为小任务)
ForkJoin特点:工作窃取
这个里面维护的是双端队列
ForkJoin
- 但是可能会出现栈内存溢出的问题
public class ForkJoinDemo extends RecursiveTask<Long> { private Long start; private Long end; //临界值 private Long temp=100000L; public ForkJoinDemo(Long start, Long end) { this.start = start; this.end = end; } @Override protected Long compute() { if ((end-start)<temp){ Long sum=0L; for (Long i=start;i<=end;i++){ sum+=1; } return sum; }else {//forkjoin long middle=(end+start)/2; ForkJoinDemo task1 = new ForkJoinDemo(start, middle); task1.fork();//把任务拆分,压入线程队列 ForkJoinDemo task2=new ForkJoinDemo(middle+1,end); task2.fork(); return task1.join()+task2.join(); } } }
public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { test1(); test2(); test3(); } public static void test1(){ long sum=0L; long start=System.currentTimeMillis(); for (long i = 0; i <1_0000_0000_0000L ; i++) { sum+=i; } long end=System.currentTimeMillis(); System.out.println("时间:"+(end-start)); } //forkjoin public static void test2() throws ExecutionException, InterruptedException { long start=System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask<Long> task= new ForkJoinDemo(0L,1_00000_0000_0000L); ForkJoinTask<Long> submit = forkJoinPool.submit(task); Long sum = submit.get(); long end=System.currentTimeMillis(); System.out.println("时间:"+(end-start)); } public static void test3(){ long start=System.currentTimeMillis(); //Stream并行流 long sum = LongStream.rangeClosed(0L, 1_0000_0000_0000L).parallel().reduce(0, Long::sum); long end=System.currentTimeMillis(); System.out.println("时间:"+(end-start)); } }