1.什么是JUC
源码 + 官方文档 面试高频问
java.util工具包、包、分类
业务:普通的线程代码 Thread
Runnable 没有返回值、效率相比于Callable相对较低
2.线程和进程
1.进程、线程
进程:一个程序,QQ.exe、Music.exe 程序的集合;
一个进程往往可以包含多个线程,至少包含一个!
java默认有几个线程?2个:main、GC(垃圾回收)
线程:开了一个进程Typora,写字,自动保存(线程负责的)
对于java而言:Thread、Runnable、Callable
java真的可以开启线程吗?
不能
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
//本地方法,调用底层的c++,Java无法直接操作硬件
private native void start0();
2.并发、并行
并发编程:并发、并行
并发(多线程操作同一个资源)
- CPU一核,模拟出来多条线程,快速交替
并行(多个人一起行走)
- CPU多核,多个线程可以同时执行;线程池
public class Test1 {
public static void main(String[] args) {
//获取CUP的核数
//CPU密集型、IO密集型
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
并发编程本质:充分利用CPU资源
3.线程有几个状态
public enum State {
//新生
NEW,
//运行
RUNNABLE,
//阻塞
BLOCKED,
//等待,死死的等
WAITING,
//超时等待
TIMED_WAITING,
//终止
TERMINATED;
}
4.wait/sleep区别
(1)来自不同的类
wait=>Object
sleep=>Thread
(2)关于锁的释放
wait会释放锁,sleep不会释放锁
(3)使用的范围不同
wait:必须在同步代码块中
sleep:可以在任何地方睡
(4)是否需要捕获异常
wait不需要捕获异常
sleep必须要捕获异常
3.Lock锁(重点)
1.传统Synchronized
package com.ff.demo01;
//基本的买票例子
/**
* 真正的多线程开发,公司中的开发
* 线程就是一个单独的资源类,没有任何附属的操作
* 1、属性、方法
*/
public class SeleTicketDemo01 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket ticket = new Ticket();
//@FunctionalInterface 函数式接口,jdk1.8 lambda表达式(参数)->{代码}
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"A").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"B").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"C").start();
}
}
//资源类OOP编程
class Ticket{
//属性,方法
private int number = 30;
//卖票方式
//synchronized 本质:队列,锁
public synchronized void sele(){
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票," +
"剩余:"+number);
}
}
}
2.Lock接口
公平锁:十分公平,可以先来后到
非公平锁:十分不公平,可以插队(默认)
package com.ff.demo01;
//基本的买票例子
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 真正的多线程开发,公司中的开发
* 线程就是一个单独的资源类,没有任何附属的操作
* 1、属性、方法
*/
public class SeleTicketDemo02 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket2 ticket = new Ticket2();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"A").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"B").start();
new Thread(()->{
for (int i=1;i<40;i++){
ticket.sele();
}
},"C").start();
}
}
//Lock锁 三部曲
//1.new ReentrantLock();
//2.lock.lock();//加锁
//3.finally => lock.unlock();//解锁
class Ticket2{
//属性,方法
private int number = 30;
Lock lock = new ReentrantLock();
public void sele(){
lock.lock();//加锁
try {
//业务代码
if (number > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票," +
"剩余:"+number);
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();//解锁
}
}
}
3.Synchronized 和 Lock锁区别
(1)Synchronized内置的关键字,Lock是一个java类
(2)Synchronized 无法判断获取锁的状态,Lock可以判断是否获取到了锁
(3)Synchronized 会自动释放锁,Lock必须要手动释放锁,如果不释放锁,死锁
(4)Synchronized 线程1(获得锁,阻塞)、线程2(等待,傻傻得等);Lock锁就不一定会等下去;
(5)Synchronized 可重入锁,不可以中断的,非公平;Lock,可重用锁,可以判断锁,非公平(可以设置);
(6)Synchronized 适合少量的代码同步问题,Lock适合锁大量的同步代码。
4.生产者和消费者
面试的:单例模式、排序算法、生产者消费者、死锁
1.生产者和消费者Synchronized版
package com.ff.pc;
/**
* 线程之间的通信问题:生产者和消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num = 0
* A num+1
* B num-1
*/
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 (Exception e){
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
}catch (Exception e){
e.printStackTrace();
}
}
},"B").start();
}
}
//判断等待,业务,通知
class Data{//数字 资源类
private int number = 0;
//+1
public synchronized void increment() throws InterruptedException {
if (number != 0){//0
//等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我+1完毕了
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
if (number == 0){//1
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我-1完毕了
this.notifyAll();
}
}
问题存在:A B C D4个线程 虚假唤醒
if 改为while 判断
package com.ff.pc;
/**
* 线程之间的通信问题:生产者和消费者问题 等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num = 0
* A num+1
* B num-1
*/
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 (Exception e){
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
}catch (Exception e){
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.increment();
}catch (Exception e){
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
}catch (Exception e){
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Data{//数字 资源类
private int number = 0;
//+1
public synchronized void increment() throws InterruptedException {
while (number != 0){//0
//等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我+1完毕了
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
while (number == 0){//1
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我-1完毕了
this.notifyAll();
}
}
2.JUC版的生产者和消费者问题
通过Lock找到Condition
代码实现:
package com.ff.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class B {
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.increment();
}catch (Exception e){
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
}catch (Exception e){
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.increment();
}catch (Exception e){
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
}catch (Exception e){
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Data2{//数字 资源类
private int number = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
//condition.await();//等待
//condition.signalAll();//唤醒全部
//+1
public void increment() throws InterruptedException {
lock.lock();
try {
while (number != 0){//0
//等待
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我+1完毕了
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//-1
public void decrement() throws InterruptedException {
lock.lock();
try {
//业务代码
while (number == 0){//1
//等待
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,我-1完毕了
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
任何一个新的技术,绝对不是仅仅覆盖了原来的技术,优势和补充
3.Condition精准的通知和唤醒线程
代码测试:
package com.ff.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A执行完调用B
* B执行完调用C
* C执行完调用A
*/
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{//数字 资源类
private Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int number = 1;//1A 2B 3C
public void printA(){
lock.lock();
try {
//业务代码,判断->执行->通知
while (number!=1){
//等待
condition1.await();
}
System.out.println(Thread.currentThread().getName()+"AAAAAA");
//唤醒指定的人B
number = 2;
condition2.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB(){
lock.lock();
try {
//业务代码,判断->执行->通知
while (number!=2){
condition2.await();
}
System.out.println(Thread.currentThread().getName()+"BBBBBBB");
number = 3;
//唤醒指定的人C
condition3.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printC(){
lock.lock();
try {
//业务代码,判断->执行->通知
while (number!=3){
condition3.await();
}
System.out.println(Thread.currentThread().getName()+"CCCCCC");
number = 1;
condition1.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
5.8锁现象
如何判断锁的是谁
对象,Class
深刻理解锁
package com.ff.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁,就是关于锁的八个问题
* 1.标准情况下,两个线程先打印 发短信还是 打电话?1.发短信 2.打电话
* 1.sendSms延迟4秒,两个线程先打印 发短信还是 打电话?1.发短信 2.打电话
*/
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 call(){
System.out.println("call");
}
public synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sendSms");
}
}
package com.ff.lock8;
import java.util.concurrent.TimeUnit;
/**
* 8锁,就是关于锁的八个问题
* 1.标准情况下,两个线程先打印 发短信还是 打电话?1.发短信 2.打电话
* 2.sendSms延迟4秒,两个线程先打印 发短信还是 打电话?1.发短信 2.打电话
* 3.增加了一个普通方法,先执行发短信还是hello?普通方法
* 4.两个对象,两个同步方法,先执行发短信还是先执行打电话?延迟时间短的先打印
*/
public class Test2 {
public static void main(String[] args) {
//两个对象,两个调用者,两把锁
Phone2 phone1= new Phone2();
Phone2 phone2 = new Phone2();
//锁的存在
new Thread(()->{
phone1.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("sendSms");
}
public synchronized void call(){
System.out.println("call");
}
//这里没有锁,不是同步方法,不受锁的影响
public void hello(){
System.out.println("hello");
}
}
package com.ff.lock8;
import java.util.concurrent.TimeUnit;
/**
* 5.增加两个静态的同步方法,只有一个对象,先打印发短信还是打电话?发短信
* 6.两个对象,增加两个静态的同步方法,先打印发短信还是打电话?发短信
*/
public class Test3 {
public static void main(String[] args) {
//两个对象的Class类模板只有一个,static,锁的是Class
Phone3 phone1= new Phone3();
Phone3 phone2= new Phone3();
//锁的存在
new Thread(()->{
phone1.sendSms();
},"A").start();
//捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
//Phone3唯一的一个class对象
class Phone3{
//synchronized锁的对象时方法的调用者
//static 静态方法
//类一加载就有了,锁的是Class
public static synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sendSms");
}
public static synchronized void call(){
System.out.println("call");
}
}
package com.ff.lock8;
import java.util.concurrent.TimeUnit;
/**
* 7.1个静态同步方法,1个普通的同步方法,一个对象,先打印发短信还是打电话?打电话
*8.1个静态同步方法,1个普通的同步方法,两个对象,先打印发短信还是打电话?打电话
*/
public class Test4 {
public static void main(String[] args) {
//两个对象的Class类模板只有一个,static,锁的是Class
Phone4 phone1= new Phone4();
Phone4 phone2= new Phone4();
//锁的存在
new Thread(()->{
phone1.sendSms();
},"A").start();
//捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
},"B").start();
}
}
//Phone3唯一的一个class对象
class Phone4{
//static 静态方法
//静态的同步方法 锁的是Class模板
public static synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sendSms");
}
//普通的同步方法 锁的是调用者
public synchronized void call(){
System.out.println("call");
}
}
小结:
new this具体的一个手机
static Class唯一的一个模板
6.集合类不安全
1.List不安全
package com.ff.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
//java.util.ConcurrentModificationException 并发修改异常
public class ListTest {
public static void main(String[] args) {
/*List<String> list = Arrays.asList("1", "2", "3");
list.forEach(System.out::println);*/
//并发下ArrayList不安全的
/**
* 解决方案:
* 1.List<String> list = new Vector<>();
* 2.List<String> list = Collections.synchronizedList(new ArrayList<>());
* 3.List<String> list = new CopyOnWriteArrayList<>();
*/
//List<String> list = new ArrayList<>();
//List<String> list = Collections.synchronizedList(new ArrayList<>());
//CopyOnWrite 写入时复制 COw 计算机程序设计领域的一种优化策略
//多个线程调用的时候,list,读取的时候,固定的,写入(覆盖)
//在写入的时候避免覆盖,造成数据问题
//读写分离
//CopyOnWriteArrayList 比 Vector 厉害在哪里?
//更快 没有使用Synchronized
List<String> list = new CopyOnWriteArrayList<>();
for (int i=1;i<=10;i++){
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
学习方法:1.先会用、2.货比三家,寻找其他解决方案、3.分析源码
2.Set不安全
package com.ff.unsafe;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* 同理可证: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 HashSet<>();
//Set<String> set = Collections.synchronizedSet(new HashSet<>());
Set<String> set =new CopyOnWriteArraySet();
for (int i=1;i<=30;i++){
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
hashSet底层是什么?
public HashSet() {
map = new HashMap<>();
}
//add set本质是map key是无法重复的
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
private static final Object PRESENT = new Object();//不变的值
3.HashMap不安全
回顾Map基本操作
7.Callable
1.可以有返回值
2.可以抛出异常
3.方法不同,run()/call()
代码测试:
package com.ff.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
*
*/
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();
new Thread().start();//怎么启动callable
MyThread thread = new MyThread();
//适配类
FutureTask futureTask = new FutureTask(thread);
new Thread(futureTask,"A").start();
Integer o = (Integer)futureTask.get();//获取Callable返回结果
System.out.println(o);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call(){
System.out.println("call()");
return 1024;
}
}
package com.ff.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
*
*/
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();
new Thread().start();//怎么启动callable
MyThread thread = new MyThread();
//适配类
FutureTask futureTask = new FutureTask(thread);
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();//结果会被缓存,效率提高
Integer o = (Integer)futureTask.get();//获取Callable返回结果
//这个get方法可能会产生阻塞 把他放在最后 或者使用异步通信来处理
System.out.println(o);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call(){
System.out.println("call()");//会打印几个call()
//耗时的操作
return 1024;
}
}
细节:
1.有缓存
2.结果可能需要等待,会阻塞
8.常用的辅助类
1.CountDownLatch
package com.ff.add;
import java.util.concurrent.CountDownLatch;
//计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6,必须要执行任务的时候,再使用
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 走了");
countDownLatch.countDown();//数量-1
},String.valueOf(i)).start();
}
countDownLatch.await();//等待计数器归零,然后再向下执行
System.out.println("Close Door");
}
}
原理:
countDownLatch.countDown();//数量-1
countDownLatch.await();//等待计数器归零
每次有线程调用countDown() 数量-1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行
2.CyclicBarrier
加法计数器
package com.ff.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.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++){
final int temp = i;
//lambda能操作到i吗?不能直接操作到
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"棵龙珠");
try {
cyclicBarrier.await();//等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3.Semaphore
Semaphore:信号量
抢车位
6车…3个停车位
package com.ff.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//线程数量:停车位
Semaphore semaphore = new Semaphore(3);
for (int i=1;i<=6;i++){
new Thread(()->{
//acquire()得到
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();
}
//release()释放
},String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire(); 获得,假设已经满了,等待被释放为止
semaphore.release(); 释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用:多个共享资源互斥的使用,并发限流,控制最大的线程数
9.读写锁
ReadWriteLock
package com.ff.rw;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 独占锁(写锁) 一次只能被一个线程占有
* 共享锁(读锁) 多个线程可以同时占有
* ReadWriteLock
* 读-读 可以共存
* 读-写 不能共存
* 写-写 不能共存
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCacheLock myCache = new MyCacheLock();
//写入
for (int i=1;i<=5;i++){
final int temp = i;
new Thread(()->{
myCache.put(temp+"",temp+"");
},String.valueOf(i)).start();
}
//读取
for (int i=1;i<=5;i++){
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
},String.valueOf(i)).start();
}
}
}
//加锁的
class MyCacheLock{
//volatile保证原子性
private volatile Map<String,Object> map = new HashMap<>();
//读写锁:更加细粒度的控制
private ReadWriteLock 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()+"写入完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
//取,读,所有人都可以读
public void get(String key){
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
/**
* 自定义缓存
*/
class MyCache{
//volatile保证原子性
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()+"写入完毕");
}
//取,读
public void get(String key){
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取完毕");
}
}
10.阻塞队列
阻塞队列:
BlockingQueue
BlockingQueue不是新的东西
什么情况下我们会使用阻塞队列:多线程并发处理,线程池
学会使用队列
添加、移除
四组API
方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add() | offer() | put() | offer( , , ) |
移除 | remove() | poll() | take() | poll( , ) |
检测队首元素 | element() | peek() | - | - |
/**
* 抛出异常
*/
public static void test1(){
//队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println("================");
//IllegalStateException: Queue full 抛出异常
//System.out.println(blockingQueue.add("d"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//java.util.NoSuchElementException 抛出异常
//System.out.println(blockingQueue.remove());
}
/**
*有返回值,没有异常
*/
public static void test2(){
//队列大小
ArrayBlockingQueue 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 blockingQueue = new ArrayBlockingQueue<>(3);
//一直阻塞
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
//blockingQueue.put("d");//队列没有位置了,一直阻塞
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
//System.out.println(blockingQueue.take());//没有这个元素
}
/**
* 等待,阻塞(等待超时)
*/
public static void test4() throws InterruptedException {
//队列的大小
ArrayBlockingQueue 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());
System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS));//等待超过两秒就退出
}
SynchronousQueue同步队列
没有容量,进去一个元素,必须等待取出来之后,才能再往里面放一个元素
put、take
package com.ff.bq;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* 同步队列
* 和其他的BlockingQueue不一样,SynchronousQueue不存储元素
* put了一个元素,必须从里面先take取出来,否则不能在put进去值
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingQeque = new SynchronousQueue<>();//同步队列
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+" put 1 ");
blockingQeque.put("1");
System.out.println(Thread.currentThread().getName()+" put 2 ");
blockingQeque.put("2");
System.out.println(Thread.currentThread().getName()+" put 3 ");
blockingQeque.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"=>"+blockingQeque.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"=>"+blockingQeque.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"=>"+blockingQeque.take());
}catch (Exception e){
e.printStackTrace();
}
},"T2").start();
}
}
11.线程池(重点)
线程池:三大方法,七大参数,四种拒绝策略
池化技术
程序的运行,本质:占用系统资源,优化资源的使用=>池化技术
线程池、连接池、内存池、对象池…创建、销毁,十分浪费资源
池化技术:事先准备好一些资源,有人要用就来我这里拿,用完以后还给我。
线程池的好处:
1.降低资源消耗
2.提高响应的速度
3.方便管理
线程复用,可以控制最大并发数,管理线程
线程池:三大方法
package com.ff.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors工具类,三大方法
public class Demo01 {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
//ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定的线程池的大小
ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩的,遇强则强,遇弱则弱
try {
for (int i = 0; i < 10; i++) {
//使用了线程池之后,使用线程池来创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " ok ");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池用完(程序结束),关闭线程
threadPool.shutdown();
}
}
}
七大参数
源码分析
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,//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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
手动创建一个线程池
public class Demo02 {
public static void main(String[] args) {
//自定义线程池
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());//队列满了,尝试和最早的竞争
try {
//最大承载:Queue+max
//超过 RejectedExecutionException
for (int i = 1; i <= 9; i++) {
//使用了线程池之后,使用线程池来创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " ok ");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池用完(程序结束),关闭线程
threadPool.shutdown();
}
}
}
四种拒绝策略
/**
* new ThreadPoolExecutor.AbortPolicy()//银行满了,还有人进来,就不处理这个人的了,抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy()//哪来的去哪里
*new ThreadPoolExecutor.DiscardPolicy()//队列满了,不会抛出异常
*new ThreadPoolExecutor.DiscardOldestPolicy()//队列满了,尝试和最早的竞争,也不会抛出异常
*/
小结和拓展
池的最大的大小如何设置
了解IO密集型,CPU密集型:(调优)
package com.ff.pool;
import org.omg.SendingContext.RunTime;
import java.util.concurrent.*;
public class Demo02 {
public static void main(String[] args) {
//自定义线程池
//最大线程到底该如何定义
//1.CPU密集型 几核,就是几,可以保证CPU效率最高
//2.IO密集型 > 判断你的任务中十分耗IO的线程
// 程序中有15个大型任务,IO十分占用资源
//获取CPU核数
System.out.println(Runtime.getRuntime().availableProcessors());
ExecutorService threadPool = new ThreadPoolExecutor(2,
Runtime.getRuntime().availableProcessors(),
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());//队列满了,尝试和最早的竞争
try {
//最大承载:Queue+max
//超过 RejectedExecutionException
for (int i = 1; i <= 9; i++) {
//使用了线程池之后,使用线程池来创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " ok ");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//线程池用完(程序结束),关闭线程
threadPool.shutdown();
}
}
}
12.四大函数式接口(必须掌握)
新时代的程序员:lambda表达式、链式编程、函数式接口、Stream流式计算
函数式接口:只有一个方法的接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//简化编程模型,在新版本的框架底层大量应用
//foreach(消费者类型的函数式接口)
代码测试
Function函数式接口
package com.ff.function;
import java.util.function.Function;
/**
* Function 函数型接口,有一个输入参数,有一个输出
* 只要是函数式接口 可以有lambda表达式简化
*/
public class Demo01 {
public static void main(String[] args) {
//工具类,输出输入的类
/*Function<String,String> function = new Function<String,String>() {
@Override
public String apply(String str) {
return str;
}
};*/
Function<String,String> function = (str)->{return str;};
System.out.println(function.apply("asd"));
}
}
Predicate断定型接口:有一个输入参数,返回值只能是布尔值
package com.ff.function;
import java.util.function.Predicate;
/**
* 断定形接口:有一个输入参数,返回值只能是布尔值
*/
public class Demo02 {
public static void main(String[] args) {
//判断字符串是否为空
/*Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String s) {
return s.isEmpty();
}
};*/
Predicate<String> predicate = (str)->{return str.isEmpty();};
System.out.println(predicate.test(""));
}
}
Consumer消费型接口
package com.ff.function;
import java.util.function.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);
};
consumer.accept("asd");
}
}
Supplier供给型接口
package com.ff.function;
import java.util.function.Supplier;
/**
* Supplier 供给型接口:没有参数,只有返回值
*/
public class Demo04 {
public static void main(String[] args) {
/*Supplier<Integer> supplier = new Supplier<Integer>() {
@Override
public Integer get() {
System.out.println("get()");
return 1024;
}
};*/
Supplier<Integer> supplier = ()->{
return 1024;
};
System.out.println(supplier.get());
}
}
13.Stream流式计算
什么是Stream流式计算
大数据:存储+计算
集合、MySql本质就是存储东西的;
计算都应该交给流来操作
package com.ff.stream;
import java.util.Arrays;
import java.util.List;
/**
* 题目要求:一分钟以内完成此题,只能用一行代码实现
* 现在有5个用户,筛选
* 1.ID必须是偶数
* 2.年龄必须大于23岁
* 3.用户名转为大写字母
* 4.用户名字母倒着排序
* 5.只输出一个用户
*/
public class Test {
public static void main(String[] args) {
User u1 = new User(1,"a",21);
User u2 = new User(2,"b",22);
User u3 = new User(3,"c",23);
User u4 = new User(4,"d",24);
User u5 = new User(6,"e",25);
//集合就是存储
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
//计算交给Stream
//链式编程
list.stream()
.filter(u->{return u.getId()%2==0;})
.filter(u->{return u.getAge()>23;})
.map(u->{return u.getName().toUpperCase();})
.sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
.limit(1)
.forEach(System.out::println);
}
}