1、什么是JUC
源码 + 官方文档 面试高频问!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qu4xws3V-1598240325200)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823100449655.png)]
Java.util 工具包
业务:普通的线程代码 Thread
Runnable:没有返回值,效率相比Callable相对较低!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yzJZo9Nb-1598240325240)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823100819350.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ccFlAOvp-1598240325242)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823100906801.png)]
2、线程和进程
线程、进程:如果不能用一句话说出来的技术,不扎实
进程:一个程序,QQ.exe Music.exe 程序的集合;
一个进程往往可以包含多个线程,至少包含一个!
Java默认有两个线程 main和GC
线程:开了一个进程Typora,写字,自动保存(线程负责的)
对于Java而言开启线程的3种方式: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();
并发、并行
并发编程:并发、并行
并发:(多线程操作同一个资源)
- CPU一核,模拟出来多条线程(天下武功、唯快不破) 快速交替;
并行:(多个人一起行走)
- CPU多核,多个线程可以同时执行;
获取CPU核数 CPU密集型、IO密集型
public class TestThread {
public static void main(String[] args) {
//获取CPU核数 CPU密集型 IO密集型
System.out.println("当前CPU核数:"+Runtime.getRuntime().availableProcessors());
}
}
并发编程的本质:充分利用CPU的资源
线程有几个状态 6个状态
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,//新生
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,//运行
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,//阻塞
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,//等待
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,//超时等待
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;//终止
}
wait/sleep区别:
1、来自不同的类
wait =>Object
sleep =>Thread
2、关于锁的释放
wait:会释放锁 sleep睡觉了,抱着锁睡觉,不会释放锁;
3、使用的范围不同
wait: 必须在同步代码块中
sleep:可以在任何地方睡
4、是否需要捕获异常
wait、sleep: 需要捕获异常
3、Lock锁
传统的Synchronized
Lock接口
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JLSJrHlH-1598240325264)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823110103460.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IMPn1tvp-1598240325266)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823110356419.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AX7G5TcE-1598240325266)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823110816528.png)]
公平锁:十分公平、先来后到;
非公平锁: 十分不公平,可以插队(默认);
package com.sqzc.demo;
/*
基本的卖票例子
1、真正的多线程开发,公司中的开发
线程就是一个单独的资源类,没有任何的附属操作!
2、属性、方法
*/
public class SaleTicket {
public static void main(String[] args) {
//并发:多个线程操作同一个资源类
Ticket1 ticket = new Ticket1();
//@FunctionalInterface 函数式接口 jdk1.8 lambda表达式 (参数)->{代码}
new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale();}, "A").start();
new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale();}, "B").start();
new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale();}, "C").start();
}
}
//资源类 OOP
class Ticket {
//属性、方法
private int number = 30;
//卖票的方式 synchronized本质:队列、锁
public synchronized void sale() {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + number-- + "张票,剩余:" + number + "张票");
}
}
}
Synchronized 和 Lock锁的区别:
1、Synchronized是一个内置的Java关键字 ,Lock是一个Java类;
2、Synchronized无法判断获取锁的状态,Lock可以判断是否获取到了锁;
3、Synchronized会自动释放锁,Lock必须手动释放锁,如果不释放锁,会造成 死锁;
4、Synchronized 线程1(获得锁)、线程2(等待、傻傻的等待) Lock不会一直等待下去;
5、Synchronized 可重入锁,不可以中断 ,非公平;Lock 可重入锁,可以判断锁 ,非公平(可以自动设置);
6、Synchronized 适合锁少量的代码同步问题,Lock适合锁大量的代码同步问题;
锁是什么?如何判断锁的是谁?
4、生产者和消费者问题
生产者和消费者问题 Synchronized 版
package com.sqzc.demo.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 (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;
//+1
public synchronized void increment() throws InterruptedException {
if (num != 0) {
//等待
this.wait();
}
num++;
System.out.println(Thread.currentThread().getName()+"==>"+num);
//通知其他线程 我加1完成了
this.notifyAll();
}
//-1
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 四个线程! 虚假唤醒?
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N4S8SUis-1598240325268)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823114412877.png)]
if 改为 while判断
JUC版 生产者和消费者问题
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MDXP3XWx-1598240325269)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823164123646.png)]
通过Lock可以找到Condition
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kqd9gQmp-1598240325271)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823164341433.png)]
代码实现
package com.sqzc.demo.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) {
Data1 data = new Data1();
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 Data1 {
private int num = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
//+1
public void increment() throws InterruptedException {
lock.lock();
try {
//业务代码
while (num != 0) {
//等待
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName() + "==>" + num);
//通知其他线程 我加1完成了
condition.signalAll();//唤醒全部
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//-1
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 e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
任何一个新的技术,绝对不是仅仅覆盖了原来的技术 ,一定会有优势和补充!!!
Condition 精准的通知和唤醒线程
代码测试
package com.sqzc.demo.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) {
Data2 data2 = new Data2();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.printA();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.printB();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data2.printC();
}
}, "C").start();
}
}
//资源类
class Data2 {
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int num = 1;//监视器 1A 2B C3
public void printA() {
lock.lock();//1、加锁
try {
//业务代码 判断-->执行-->通知
while (num != 1) {
//等待
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "现在是A在执行...");
//唤醒 唤醒指定的人 B
num = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
public void printB() {
lock.lock();//1、加锁
try {
//业务代码 判断-->执行-->通知
while (num != 2) {
//等待
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "现在是B在执行...");
//唤醒 唤醒指定的人 B
num = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
public void printC() {
lock.lock();//1、加锁
try {
//业务代码 判断-->执行-->通知
while (num != 3) {
//等待
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "现在是C在执行...");
//唤醒 唤醒指定的人 B
num = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//解锁
}
}
}
5、8锁现象
任何判断锁的是谁 !永远知道什么是锁,锁到底锁的是谁!
6、集合类不安全
List不安全
package com.sqzc.demo.unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/*
java.util.ConcurrentModificationException 并发修改异常
解决方法:
1、List<String> list = new Vector<>()
2、List<String> list = Collections.synchronizedList(new ArrayList<>());
3、List<String> list = new CopyOnWriteArrayList<>();
CopyOnWrite:写入时复制 COW 计算机程序设计领域的一种优化策略
多个线程调用的时候,list,读取的时候,固定的,写入(覆盖) 在写入的时候避免覆盖 造成数据问题 读写分离
Vector(synchronized)效率低 && CopyOnWriteArrayList(Lock锁) 效率高
*/
public class UnsafeList {
public static void main(String[] args) {
//并发下ArrayList不安全
/*List<String> list = new ArrayList<String>();*/
//解决方案
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();
}
}
}
Set不安全
package com.sqzc.demo.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 UnSafeSet {
public static void main(String[] args) {
/*Set<String> set = new HashSet<>();*/
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 0; i < 100; 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 本质就是map key是无法重复的;
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
private static final Object PRESENT = new Object();//不变的值
Map不安全
回顾HashMap的基本操作
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WwhkGnlV-1598240325273)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823183426999.png)]
7、Callable
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IMAl2rPQ-1598240325274)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200823184500257.png)]
1、可以有返回值
2、可以抛出异常
3、方法不同 run() / call()
代码测试
package com.sqzc.demo.callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThread myThread = new MyThread();
//适配类
FutureTask<String> futureTask = new FutureTask<>(myThread);
new Thread(futureTask,"A").start();//怎么启动Callable*/
new Thread(futureTask,"B").start();//结果会被缓存
//获取Callable返回结果
String s = futureTask.get();//get方法可能会产生阻塞 放到最后 或者使用异步通信处理
System.out.println(s);
/*new Thread(new FutureTask<String>(myThread)).start();//怎么启动Callable*/
}
}
class MyThread implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("call()");
return "123";
}
}
细节
1、有缓存
2、结果可能要等待,会阻塞。
8、常用的辅助类
8.1. CountDownLatch(减法计数器)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hmqE9PPu-1598240325275)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200824103714971.png)]
代码测试
package com.sqzc.demo.CountDownLatch;
import java.util.concurrent.CountDownLatch;
/*
计数器
*/
public class TestCountDownLatch {
public static void main(String[] args) throws InterruptedException {
//倒计时 总数是6 必须要执行任务的时候,再使用。
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go out");
countDownLatch.countDown();//数量 -1
},String.valueOf(i)).start();
}
countDownLatch.await();//等待计数器归0,然后再向下执行
System.out.println("Close Door");
}
}
原理:
countDownLatch.countDown()
;//数量 -1
countDownLatch.await()
;//等待计数器归0,然后再向下执行
每次有线程调用countDown()数量 -1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行。
8.2. CyclicBarrier(加法计数器)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Clu4myN0-1598240325275)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200824104924022.png)]
代码测试
package com.sqzc.demo.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/*
加法计数器
*/
public class TestCyclicBarrier {
public static void main(String[] args) {
/*集齐7颗龙珠,召唤神龙*/
//召唤龙珠线程
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();
}
},String.valueOf(i)).start();
}
}
}
8.3. Semaphore(计数信号量)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NwOBDkEz-1598240325277)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200824105715683.png)]
代码测试:
package com.sqzc.demo.Semaphore;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/*
example:停车位
限流的时候可以用!!!
*/
public class TestSemaphore {
public static void main(String[] args) {
//线程数量permits 停车位3个
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(3);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//release();释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
原理
semaphore.acquire();
获得,假设已经满了,等待被释放为止!
semaphore.release();
释放,会将当前的信号量释放+1,然后唤醒等待的线程!
*作用:*多个共享资源互斥使用!并发限流,控制最大线程数。
9、读写锁
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ombc0Cpc-1598240325277)(C:\Users\君莫笑\AppData\Roaming\Typora\typora-user-images\image-20200824111216656.png)]
代码测试:
package com.sqzc.demo.ReadWriteLock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/*
读写锁(ReadWriteLock)
读-读 可以共存
读-写 不能共存
写-写 不能共存
PS:
独占锁(写锁): 一次只能被一个线程占有
共享锁(读锁): 多个线程可以同时占有
*/
public class TestReadWriteLock {
public static void main(String[] args) {
MyCatch myCatch = new MyCatch();
//写入
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCatch.put(temp + "", temp);
}, String.valueOf(i)).start();
}
//读取
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(() -> {
myCatch.get(temp + "");
}, String.valueOf(i)).start();
}
}
}
/*
自定义缓存
*/
class MyCatch {
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() + "读取成功!");
}
}
//加锁缓存
class MyCatchLock {
private volatile Map<String, Object> map = new HashMap<>();
//读写锁 更加细粒度的控制
private ReadWriteLock lock = new ReentrantReadWriteLock();
//存 写入的时候,只希望同时只有一个线程写
public void put(String key, Object value) {
lock.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 {
lock.writeLock().unlock();//解锁
}
}
//取 所有人都可以读
public void get(String key) {
lock.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 {
lock.readLock().unlock();//解锁
}
}
}