JUC并发编程
1、什么是JUC
JUC就是java.util.concurrent
包下面的类方法。
2、线程和进程
- 一个进程包含多个线程,Java不能创建线程,是通过
private native void start0();
来进行创建。 - CPU 单核是通过线程之间快速交替并行,实际同一时间只有一个线程在运行。
- CPU 多核则是多个线程同时执行,可创建线程池。
public static void main(String[] args) {
// 获取Cpu核数
System.out.println(Runtime.getRuntime().availableProcessors()); ;
}
并发编程的本质: 充分利用CPU的资源
线程的状态
public enum State {
// 新创建,尚未启动的线程状态
NEW,
// 运行时
RUNNABLE,
// 被阻塞
BLOCKED,
// 等待中
WAITING,
// 定时等待中
TIMED_WAITING,
// 终止的线程状态/已完成
TERMINATED;
}
wait/sleep 区别
1、来自不同的类
wait => Object
sleep => Thread
2、关于锁的释放
wait会释放锁,sleep不会释放
3、使用范围
wait 必须在同步代码块使用
sleep 任何地方都可使用
3、lock锁
传统的synchronized
Lock接口
package com.jdk.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 09:32:00
*/
public class SaleTicketDemo {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(() -> {
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"A").start();
new Thread(() -> {
for (int i = 0; i < 50; i++) {
ticket.sale();
}
},"B").start();
new Thread(() -> {
for (int i = 0; i < 50; i++) {
ticket.sale();
}
},"C").start();
}
}
class Ticket {
private int number = 50;
Lock lock = new ReentrantLock();
public synchronized void sale() {
lock.lock();
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票,剩余: " + number);
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
synchronized 和 Lock 区别
1、synchronized 内置的java关键字,Lock是一个类。
2、synchronized 无法获取锁的状态,Lock可以判断是否获取锁。
3、synchronized会自动释放锁,lock需要手动释放锁。
4、synchronized 线程1(获得锁,阻塞)、线程2(等待、傻傻的等); Lock锁不会一直等待下去;
5、synchronized 可重入锁,不可以中断的,非公平;Lock,可重入锁,可以判断锁;非公平(自己可以设置)
6、synchronized 适合少量的代码同步问题,Lock适合大量代码同步问题。
4、生产者和消费者问题
synchronized 版本
多生产者,多消费者的问题。
if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
while判断标记,解决了线程获取执行权后,是否要运行!
notify:只能唤醒一个线程,如果本方唤醒了本方,没有意义。而且while判断标记+notify会导致死锁。
notifyAll解决了本方线程一定会唤醒对方线程的问题。
package com.jdk.thread;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:00:00
*/
public class ProducerConsumer {
public static void main(String[] args) {
Goods goods = new Goods();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "C").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "D").start();
}
}
class Goods {
private int num = 0;
// 当为0 的时候就+1
public synchronized void increment() throws InterruptedException {
if (num != 0) {
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName() + "--->" + num);
this.notifyAll();
}
// 当不为0 的时候就-1
public synchronized void decrement() throws InterruptedException {
if (num == 0) {
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "--->" + num);
this.notifyAll();
}
}
再生产者和消费者只用一个的时候不会出错,当存在多个时则会出错。是因为if判断会出现虚假唤醒,导致不该运行的线程运行,出现数据错误的情况。
解决办法: while判断标记,解决了线程获取执行权后,是否要运行。
package com.jdk.thread;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:00:00
*/
public class ProducerConsumer {
public static void main(String[] args) {
Goods goods = new Goods();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "C").start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "D").start();
}
}
class Goods {
private int num = 0;
// 当为0 的时候就+1
public synchronized void increment() throws InterruptedException {
while (num != 0) {
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName() + "--->" + num);
this.notifyAll();
}
// 当不为0 的时候就-1
public synchronized void decrement() throws InterruptedException {
while (num == 0) {
this.wait();
}
num--;
System.out.println(Thread.currentThread().getName() + "--->" + num);
this.notifyAll();
}
}
JUC版的生产者和消费者
package com.jdk.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:00:00
*/
public class ProducerConsumer2 {
public static void main(String[] args) {
Goods2 goods = new Goods2();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.increment();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.increment();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.decrement();
}
}, "D").start();
}
}
class Goods2 {
private int num = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
// 当为0 的时候就+1
public void increment() {
lock.lock();
try {
while (num != 0) {
try {
condition.await(); // 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println(Thread.currentThread().getName() + "--->" + num);
condition.signalAll(); //唤醒全部
}finally {
lock.unlock();
}
}
// 当不为0 的时候就-1
public void decrement(){
lock.lock();
try {
while (num == 0) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num--;
System.out.println(Thread.currentThread().getName() + "--->" + num);
condition.signalAll();
}finally {
lock.unlock();
}
}
}
任何一个新的技术,绝不是覆盖原来的技术,必定有一定升级
如何保证顺序执行 A->B->C->D
业务->执行->通知
package com.jdk.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:00:00
*/
public class ProducerConsumer3 {
public static void main(String[] args) {
Goods3 goods = new Goods3();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.a();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.b();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
goods.c();
}
}, "C").start();
}
}
class Goods3 {
private int num = 0;
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
public synchronized void a() {
lock.lock();
try {
while (num != 0) {
try {
condition1.await(); // a等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = 1;
System.out.println(Thread.currentThread().getName() + "--->" + "AAAAAAA");
condition2.signal(); //唤醒b
}finally {
lock.unlock();
}
}
public void b(){
lock.lock();
try {
while (num != 1) {
try {
condition2.await(); // b等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = 2;
System.out.println(Thread.currentThread().getName() + "--->" + "BBBBBBB");
condition3.signal(); //唤醒c
}finally {
lock.unlock();
}
}
public void c() {
lock.lock();
try {
while (num != 2) {
try {
condition3.await(); // c等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = 0;
System.out.println(Thread.currentThread().getName() + "--->" + "CCCCCCC");
condition1.signal(); //唤醒a
}finally {
lock.unlock();
}
}
}
5、8锁现象
深刻理解锁
1、多个线程使用同一个对象,多个线程就是使用一把锁,先调用的先执行!
2、多个线程使用同一个对象,多个线程就是使用一把锁,先调用的先执行,即使在某方法中设置了阻塞。
3、多个线程有锁与没锁-随机执行
package com.jdk.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁关于锁的8个问题
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:37:00
*/
public class Test1 {
public static void main(String[] args) {
// 锁的是方法调用者 发短信->打电话
Phone phone = new Phone();
new Thread(phone::sendSms, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(phone::call, "B").start();
}
}
class Phone {
// synchronized 锁的对象是方法调用者
// 两个方法用同一个锁,谁先拿到谁先用
public synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
4、多个线程使用多把锁-随机执行
package com.jdk.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁关于锁的8个问题
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:37:00
*/
public class Test2 {
public static void main(String[] args) {
// 对两个对象进行加锁 先打电话->发短信
Phone2 phone = new Phone2();
Phone2 phone2 = new Phone2();
new Thread(phone::sendSms, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(phone2::call, "B").start();
}
}
class Phone2 {
// synchronized 锁的对象是方法调用者
// 两个方法用同一个锁,谁先拿到谁先用
public synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
5、Class锁:多个线程使用一个对象-顺序执行
6、Class锁:多个线程使用多个对象-顺序执行
被 synchronized 和 static 同时修饰的方法,锁的对象是类的 class 对象,是唯一的一把锁。线程之间是顺序执行。
锁Class和锁对象的区别:
- 1、Class 锁 ,类模版,只有一个。
- 2、对象锁 , 通过类模板可以new 多个对象。
如果全部都锁了Class,那么这个类下的所有对象都具有同一把锁。
package com.jdk.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁关于锁的8个问题
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:37:00
*/
public class Test3 {
public static void main(String[] args) {
// 类模板初始化的时候就创建了,所以即使是两个对象,类模板也是一个。 发短信->打电话
Phone3 phone = new Phone3();
Phone3 phone2 = new Phone3();
new Thread(() -> {
phone.sendSms();
}, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
phone2.call();
}, "B").start();
}
}
class Phone3 {
// 锁的是class类模板
public static synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
// 锁的是class类模板
public static synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
7、Class锁与对象锁:多个线程使用一个对象-随机执行
8、 Class锁与对象锁:多个线程使用多个对象-随机执行
package com.jdk.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁关于锁的8个问题
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 10:37:00
*/
public class Test4 {
public static void main(String[] args) {
// 类模板初始化的时候就创建了,所以即使是两个对象,类模板也是一个。 打电话->发短信
Phone4 phone = new Phone4();
new Thread(() -> {
phone.sendSms();
}, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
phone.call();
}, "B").start();
}
}
class Phone4 {
// 锁的是class类模板
public static synchronized void sendSms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
// 普通同步方法
public synchronized void call() {
System.out.println("打电话");
}
}
6、集合不安全
List不安全
package com.jdk.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 11:23:00
*/
public class ListTest {
//可能会报 java.util.ConcurrentModificationException 同步修改的异常
public static void main(String[] args) {
// 解决办法
// 1、 List<String> list = new Vector<>();
// 2、 List<String> list = Collections.synchronizedList(new ArrayList<>());
// 3、 List<String> list = new CopyOnWriteArrayList<>();
// CopyOnWrite 写入时复制 COW 计算机程序设计领域的一种优化策略;
// 多个线程调用的时候,list读取是固定的,写入(覆盖)
// 在写入的时候避免覆盖,造成数据问题
// 读写分离
// CopyOnWriteArrayList 比 Vector 一个用Lock加锁一个用sychronized加锁
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 300; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
Set不安全
package com.jdk.unsafe;
import cn.hutool.core.collection.ConcurrentHashSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 11:39:00
*/
public class SetTest {
public static void main(String[] args) {
// ConcurrentModificationException
//解决方案
// 1、 Set<String> stringSet = Collections.synchronizedSet(new HashSet<>());
// 2、 Set<String> stringSet = new CopyOnWriteArraySet<>();
Set<String> stringSet = new CopyOnWriteArraySet<>();
for (int i = 0; i < 300; i++) {
new Thread(() -> {
stringSet.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(stringSet);
},String.valueOf(i)).start();
}
}
}
hashSet底层是什么?
public HashSet() {
map = new HashMap<>();
}
// add
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
Map 不安全
package com.jdk.unsafe;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 12:26:00
*/
public class MapTest {
public static void main(String[] args) {
// map是这样用吗? 不是,工作中不用HashMap
// 默认等价于什 new HashMap<>(16,0.75)
// 出现 ConcurrentModificationException
// 解决方案:
// 1、 Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
// 2、 Map<String, String> map = new ConcurrentHashMap<>();
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i <= 300; 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 方法不同 call()
package com.jdk.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 12:41:00
*/
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();
FutureThread myThread = new FutureThread();
FutureTask<Integer> futureTask = new FutureTask<>(myThread);
new Thread(futureTask,"A").start();
Integer result = futureTask.get();
System.out.println(result);
}
}
class FutureThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call");
return 1024;
}
}
细节:
1、有缓存
2、结果可能需要等待、会阻塞
8、常用的辅助类
8.1、CountDownLatch
package com.jdk.threadSafe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* 计数器
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 15:57:00
*/
public class CountDownLatchDemo {
// private static volatile CountDownLatch countDownLatch = new CountDownLatch(6);
public static void main(String[] args) throws InterruptedException {
// 计数器 比如: 6个人 最后一个人出门才关上门
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + "出来了");
}, String.valueOf(i)).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("close the door");
}
}
原理:
countDownLatch.countDown();
//数量-1
countDownLatch.await();
//等待计数器归0的时候
8.2、CyclicBarrier
package com.jdk.threadSafe;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 16:22:00
*/
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()-> {
System.out.println("开始召回神龙...");
});
for (int i = 1; i <= 7; i++) {
int finalI = i;
new Thread(() -> {
System.out.println("已集齐" + finalI + "颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
8.3、Semaphore
package com.jdk.threadSafe;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* 抢车位
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 16:35:00
*/
public class SemaphoreDemo {
public static void main(String[] args) {
// 线程数量: 停车位 3个车位
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
int finalI = i;
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "抢到车位");
TimeUnit.SECONDS.sleep(finalI *2);
System.out.println(Thread.currentThread().getName() + "离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire();
获得,假设如果已经满了,等待被释放为止。
semaphore.release();
释放,会将当前的信号量释放 +1,然后唤醒等待的线程。
9、读写锁
package com.jdk.thread;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 16:53:00
*/
public class ReentrantReadWriteLockDemo {
public static void main(String[] args) {
MyCache cache = new MyCache();
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
for (int i = 1; i <= 10; i++) {
final int temp = i;
new Thread(() -> {
try {
readWriteLock.writeLock().lock();
cache.put("demo" + temp, "demo" + temp);
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 10; i++) {
final int temp = i;
new Thread(() -> {
try {
readWriteLock.readLock().lock();
Object o = cache.get("demo" + temp);
System.out.println(o);
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}, String.valueOf(i)).start();
}
}
}
class MyCache {
private volatile Map<String, Object> map = new HashMap<>();
public void put(String key, String value) {
System.out.println(Thread.currentThread().getName() + "写入开始");
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入结束");
}
public Object get(String key) {
System.out.println(Thread.currentThread().getName() + "读取开始");
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取结束");
return o;
}
}
10、阻塞队列
阻塞
队列满了,放入数据必须阻塞等待。
队列空了,取数据必须阻塞等待。
队列
Queue
1、Deque 双端队列
2、BlockQueue 阻塞队列
3、AbstractQueue 非阻塞队列
什么情况使用队列: 多线程并发,线程池。
学会使用队列
添加、移除
四组API
ArrayBlockingQueue
方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer | put | offer |
移除 | remove | poll | take | poll |
获取队首元素 | element | peek |
package com.jdk.blockQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 17:18:00
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
test4();
}
/**
* 抛出异常
*/
private static void test1() {
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("A"));
System.out.println(blockingQueue.add("B"));
System.out.println(blockingQueue.add("C"));
// IllegalStateException: Queue full 抛出异常
// System.out.println(blockingQueue.add("D"));
System.out.println(blockingQueue.element());
System.out.println("================");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// NoSuchElementException
// System.out.println(blockingQueue.remove());
}
/**
* 有返回值
*/
private 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"));
System.out.println("=====================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
/**
* 等待,阻塞(一直阻塞)
*/
private static void test3() throws InterruptedException {
ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("A");
blockingQueue.put("B");
blockingQueue.put("C");
// blockingQueue.put("D");
System.out.println("=====================");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
// System.out.println(blockingQueue.take());
}
/**
* 等待超時
*/
private 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));
System.out.println("=====================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
}
SynchronousQueue
package com.jdk.blockQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* 同步队列
* <p>
* 和其他BlockingQueue不一样,SynchronousQueue 不存储元素
* put一个元素,必须从里面先take取出来,否则不能put进去
*
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月26日 17:38:00
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> queue = new SynchronousQueue<>();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "put a");
queue.put("a");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + "put b");
queue.put("b");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "put c");
queue.put("c");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T1").start();
new Thread(() -> {
try {
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());
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T2").start();
}
}
11、线程池
池化技术
线程池、连接池、内存池、对象池。。。
线程池的好处:
1、降低资源消耗
2、提高响应速度
3、方便管理
// Executors 工具类、3大方法
public static void main(String[] args) {
// ExecutorService service = Executors.newFixedThreadPool(3); //创建一个固定的线程池大小
// ExecutorService service = Executors.newSingleThreadExecutor(); //单个线程
ExecutorService service = Executors.newCachedThreadPool(); //可伸缩
service.execute(
() -> {
// ... do something inside runnable task
});
service.shutdown();
}
7大参数
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // 21亿
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去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学 更加明确线程池的运行规则,规避资源耗尽的风险。
手动创建线程池
package com.jdk.pool;
import java.util.concurrent.*;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月27日 10:13:00
*/
public class Demo02 {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(
2,
5,
3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
for (int i = 1; i <= 9; i++) {
executorService.execute(()-> {
System.out.println(Thread.currentThread().getName()+"正在执行。。。");
});
}
}
}
4种拒绝策略
AbortPolicy :队列满了,还有数据进来则抛出异常 RejectedExecutionException
DiscardPolicy: 队列满了,还有线程进来,不会报异常
CallerRunsPolicy: 哪来的去哪里执行
DiscardOldestPolicy:尝试和最早的竞争,也不会抛出异常
小结 (优化)
CPU密集型:计算密集型任务同时进行的数量应当等于CPU的核心数。
IO密集型:IO密集型任务指任务需要执行大量的IO操作,涉及到网络、磁盘IO操作,对CPU消耗较少,其消耗的主要资源为IO。 通常就需要开CPU核心数两倍的线程
12、四大函数接口 (必须掌握)
新时代的程序员: 函数式接口、Lambda表达式、链式编程、Stream流式计算
函数式接口: 只有一个方法的接口
*/
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Function
package com.jdk.function;
import java.util.function.Function;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月27日 14:38:00
*/
public class Demo01 {
public static void main(String[] args) {
// Function function = new Function() {
// @Override
// public Object apply(Object o) {
// return o;
//
// }
// };
Function function = o -> o;
System.out.println(function.apply("sssss"));
}
}
Predicate
package com.jdk.function;
import java.util.Objects;
import java.util.function.Predicate;
/**
* 断定性接口
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月27日 14:40:00
*/
public class Demo02 {
public static void main(String[] args) {
// Predicate predicate = new Predicate() {
// @Override
// public boolean test(Object o) {
// return Objects.isNull(o);
//
// }
// };
Predicate predicate = o -> Objects.isNull(o);
System.out.println(predicate.test(""));
}
}
Consumer
package com.jdk.function;
import java.util.function.Consumer;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月27日 14:42:00
*/
public class Demo03 {
public static void main(String[] args) {
// Consumer consumer = new Consumer() {
// @Override
// public void accept(Object o) {
// System.out.println(o);
// }
// };
Consumer consumer = o -> System.out.println(o);
consumer.accept("acbbbb");
}
}
Supplier
package com.jdk.function;
import java.util.function.Supplier;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月27日 14:43:00
*/
public class Demo04 {
public static void main(String[] args) {
// Supplier supplier = new Supplier<Integer>() {
// @Override
// public Integer get() {
// return 1024;
// }
// };
Supplier supplier = (Supplier<Integer>) () -> 1024;
System.out.println(supplier.get());
}
}
Fork/Join
特点:工作窃取
维护的是一个双端对流
ForkJoin 适合大数据
package com.jdk.threadSafe;
import java.util.concurrent.RecursiveTask;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月28日 09:41:00
*/
public class ForkJoinDemo extends RecursiveTask<Long> {
private Long start;
private Long end;
private Long temp = 1000L;
public ForkJoinDemo(Long start, Long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long result = 0;
if ((end - start) > temp) {
long middle = (start + end) / 2;
ForkJoinDemo left = new ForkJoinDemo(start, middle);
ForkJoinDemo right = new ForkJoinDemo(middle + 1, end);
left.fork();
right.fork();
result = left.join() + right.join();
} else {
for (long i = start; i < end; i++) {
result += i;
}
}
return result;
}
}
异步回调
package com.jdk.sync;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author pengyangyan
* @version 1.0.0
* @date 2021年04月28日 09:54:00
*/
public class AsyncDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 没有返回值
// CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()-> {
// try {
// TimeUnit.SECONDS.sleep(2);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"runAsync=>void");
// });
// 没有返回值
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync=>void");
return 1024/0;
});
System.out.println(completableFuture.whenComplete((t, u) -> {
System.out.println("t->" + t);
System.out.println("u->" + u);
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 1011;
}).get());
}
}
JVM
谈谈对volatile的理解
volatile 是java虚拟机提供轻量级同步机制
1、保证可见性
2、不保证原子性
3、禁止指令重排
什么是JVM
JVM: java内存模型,一种概念
关于JVM的一些同步约定:
1、线程解锁前,必须把共享变量立刻刷回主存。
2、线程加锁前,必须读取主存中最新的到工作内存中。
3、加锁和解锁是同一把锁。
线程 ** 工作内存 主内存**
CAS
原子性