JUC并发
目录
1.什么是JUC
JUC就是 java.util
下的工具包、包、分类等。
业务:普通的线程代码
- Thread
- Runnable 没有返回值,效率比Callable相对较低
- Callable 有返回值!
2.线程和进程
线程、进程,如果不能使用一句话说出来的技术,不扎实!
- 进程:一个程序,QQ.exe Music.exe 程序的集合;
- 一个进程往往可以包含多个线程,至少包含一个!
- Java默认有2个线程? mian、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();
并发和并行
并发编程:并发、并行
并发(多线程操作同一个资源)
- CPU一核,模拟出来多条线程,快速交替
并行(多个人一起行走)
- CPU多核,多个线程可以同时执行;eg:线程池!
package demo01;
public class Test01 {
public static void main(String[] args) {
//获取CPU的核数
//CPU密集型,IO密集型
System.out.println(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.Synchronized锁
传统 Synchronized锁
来看一个多线程卖票例子
package demo01;
/*
基本的卖票例子
*/
/**
* 真正的多线程开发,公司中的开发
* 线程就是一个单独的资源类,没有任何附属的操作
* 1.属性、方法
*/
public class SaleTicketDemo01 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket ticket = new Ticket();
//@FunctionalInterface 函数式接口 jdk8 lamdba表达式(参数) -> {代码}
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();
}
}
//资源类 OOP
class Ticket{
//属性、方法
private int number = 50;
//买票的方式
//sychronized 本质:队列,锁
public synchronized void sale(){
if (number >0){
System.out.println(Thread.currentThread().getName() + "卖出了" +(number --)+ "票,剩余:" + number);
}
}
}
4.LOCK锁(重点)
LOCK接口
- 公平锁:十分公平,可以先来后到
- 非公平锁:十分不公平,可以插队(默认)
使用LOCK在写刚才的列子
package demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTicketDemo02 {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,把资源类丢入线程
Ticket2 ticket = new Ticket2();
//@FunctionalInterface 函数式接口 jdk8 lamdba表达式(参数) -> {代码}
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();
}
}
/**
* 1. new ReentrantLock();
* 2. lock.lock(); //加锁
* 3. finally{
* lock.unlock();//解锁
* }
*/
class Ticket2{
//属性、方法
private int number = 50;
//买票的方式
//LOCK锁
Lock lock = new ReentrantLock();
public void sale(){
lock.lock();;//加锁
try{
//业务代码块
if (number >0){
System.out.println(Thread.currentThread().getName() + "卖出了" +(number --)+ "票,剩余:" + number);
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();//解锁
}
}
}
Synchroized和Lock的区别
1.Synchroized 是内置的Java关键字,Lock是一个Java类
2.Synchroized 无法判断获取锁的状态,Lock可以判断获取锁的状态
3.Synchroized 会自动释放锁,Lock必须要手动释放锁!如果不释放锁,死锁
4.Synchroized 线程1(获得锁、阻塞)、线程2(等待);Lock就不一定会等待下去(trylock 尝试获取锁)
5.Synchroized可重入锁,不可以中断的,非公平;Lock,可重入锁,可以判断锁,非公平(可以自己设置)
6.Synchroized适合锁少量的代码同步问题,Lock适合锁大量的同步代码!
锁是什么,如何判断锁的是谁?
5.生产者和消费者问题
面试常考的问题:单例模式、排序算法、生产者和消费者、死锁
生产者和消费者问题 Synchronized 版
package demo02;
import sun.awt.windows.ThemeReader;
/**
线程之间的通信问题:生产者和消费者问题
线程交替执行:A B操作同一个变量 num = 0
A num+1
B num-1
*/
public class SYProducers {
public static void main(String[] args) {
Date date = new Date();
//执行+1
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
//执行-1
new Thread(()->{
for (int i =0;i<10;i++){
try {
date.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
}
}
//判断等待,业务,通知
class Date{//数字 资源类
private int number = 0;
//+1
public synchronized void increment() throws InterruptedException {
if (number !=0){
//等待
this.wait();
}
number++;
//通知其他线程,我+1完毕
System.out.println(Thread.currentThread().getName() +"=>" + number);
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
if (number == 0){
//等待
this.wait();
}
number --;
//通知其他线程,我-1完毕
System.out.println(Thread.currentThread().getName() +"=>" + number);
this.notifyAll();
}
}
问题存在,A B C D 4 个线程! 虚假唤醒
if判断改为while判断
package demo02;
import sun.awt.windows.ThemeReader;
/**
线程之间的通信问题:生产者和消费者问题
线程交替执行:A B操作同一个变量 num = 0
A num+1
B num-1
*/
public class SYProducers {
public static void main(String[] args) {
Date date = new Date();
//执行+1
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
//执行-1
new Thread(()->{
for (int i =0;i<10;i++){
try {
date.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Date{//数字 资源类
private int number = 0;
//+1
/*
假设 number此时等于1,即已经被生产了产品
如果这里用的是if判断,如果此时A,C两个生产者线程争夺increment()方法执行权
假设A拿到执行权,经过判断number!=0成立,则A.wait()开始等待(wait()会释放锁),然后C试图去执行生产方法,
但依然判断number!=0成立,则C.wait()开始等待(wait()会释放锁)
碰巧这时候消费者线程线程B/D去消费了一个产品,使number=0然后,B/D消费完后调用this.notifyAll();
这时候2个等待中的生产者线程继续生产产品,而此时number++ 执行了2次
同理,重复上述过程,生产者线程继续wait()等待,消费者调用this.notifyAll();
然后生产者继续超前生产,最终导致‘产能过剩’,即number大于1
if(number != 0){
// 等待
this.wait();
}*/
public synchronized void increment() throws InterruptedException {
while (number !=0){
//等待
this.wait();
}
number++;
//通知其他线程,我+1完毕
System.out.println(Thread.currentThread().getName() +"=>" + number);
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
while (number == 0){
//等待
this.wait();
}
number --;
//通知其他线程,我-1完毕
System.out.println(Thread.currentThread().getName() +"=>" + number);
this.notifyAll();
}
}
JUC版的生产者和消费者问题
通过Lock可以找到一个Condition方法
代码实现
package demo02;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LOCKProducers {
public static void main(String[] args) {
Date2 date = new Date2();
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
//执行-1
new Thread(()->{
for (int i =0;i<10;i++){
try {
date.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i =0; i<10;i++){
try {
date.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
//判断等待,业务,通知
class Date2 {//数字 资源类
private int number = 0;
//+1
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
//condition.await();//等待
//condition.signalAll();//唤醒全部
lock.lock();
try{
while (number != 0) {
//等待
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
condition.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
//-1
public void decrement() throws InterruptedException {
lock.lock();
try{
while (number == 0) {
//等待
condition.await();
}
number--;
//通知其他线程,我-1完毕
System.out.println(Thread.currentThread().getName() + "=>" + number);
condition.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
任何一个新的技术,绝对不是仅仅只是覆盖了原来的技术,是有其对旧技术的优势和补充!
Condition 精准的通知和唤醒线程
有序执行线程
package demo02;
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 data3 = new Data3();
new Thread(()->{
for (int i =0; i< 10; i++){
data3.printA();
}
},"A").start();
new Thread(()->{
for (int i =0; i< 10; i++){
data3.printB();
}
},"B").start();
new Thread(()->{
for (int i =0; i< 10; i++){
data3.printC();
}
},"C").start();
}
}
class Data3{//资源lock
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int number = 1;
public void printA(){
lock.lock();
try{
while(number != 1){
//等待
condition1.await();
}
System.out.println(Thread.currentThread().getName() + " => A");
//唤醒指定的B
condition2.signal();
number = 2;
}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() + " => B");
condition3.signal();
number = 3;
}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() + " => C");
condition1.signal();
number
= 1;
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
//生产线:下单->支付操作->交易->物流
}
6.8锁现象
前面提出一个问题:如何判断锁的是谁!知道什么是锁,锁到底锁的是谁!
深刻理解我们的锁
package lock8;
import java.util.concurrent.TimeUnit;
/*
8锁就是关于锁的8个问题
1.标准情况下,两个线程先打印,发短信还是打电话?
1/sendSms
2/call
2.sendSms延迟1秒,两个线程先打印,发短信还是打电话?
1/sendSms
2/call
*/
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{
//synchroized 锁的对象是方法的调用者
//两个方法用的是同一个锁
//谁先拿到谁执行
public synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sendSms");
}
public synchronized void call(){
System.out.println("call");
}
}
普通方法是没有锁的,不受所得影响,正常执行即可
package lock8;
import java.util.concurrent.TimeUnit;
/**
* 3.增加了一个普通方法,其中发短信延迟了4秒,是先执行发短信还是hello?
* 1/hello 2/sendSms
* 4.两个对象,两个同步方法,先发短信还是先打电话?
* 1/call 2/sendSms
*/
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{
//synchroized 锁的对象是方法的调用者
//两个方法用的是同一个锁
//谁先拿到谁执行
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");
}
}
Static是类加载时候执行的,带有static的同步方法是类锁
package lock8;
import java.util.concurrent.TimeUnit;
/**
* 5.增加两个静态的同步方法,只有一个对象,先发短信还是先打电话?
* 1/sendSms 2/call
* 6.两个对象,加两个静态的同步方法,先发短信还是先打电话?
* 1/sendSms 2/call
*/
public class Test3 {
public static void main(String[] args) {
Phone3 phone = new Phone3();
Phone3 phone3 = new Phone3();
//
new Thread(()->{
phone.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone3.call();
},"B").start();
}
}
class Phone3{
//synchroized 锁的对象是方法的调用者
//两个方法用的是同一个锁
//谁先拿到谁执行
//static静态方法
//类加载就有了
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");
}
}
7/8 两种情况下,都是先执行打电话,后执行发短信,因为二者锁的对象不同,静态同步方法锁的是Class类模板,普通同步方法锁的是实例化的对象,所以不用等待前者解锁后 后者才能执行,而是两者并行执行,因为发短信休眠4s, 所以打电话先执行
package lock8;
import java.util.concurrent.TimeUnit;
/**
* 6.一个普通同步方法,一个静态同步方法,只有一个对象,先发短信,先打电话?
* 1/call 2/sendSms
* 7.一个普通同步方法,一个静态同步方法,两个对象,先发短信,先打电话?
* 1/call 2/sendSms
*/
public class Test4 {
public static void main(String[] args) {
Phone4 phone = new Phone4();
Phone4 phone4 = new Phone4();
new Thread(()->{
phone.sendSms();
},"A").start();
// 捕获
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone4.call();
},"B").start();
}
}
class Phone4{
//锁的是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 具体的一个手机
- staic:锁的是Class 唯一的一个模板
7.集合类不安全
List- 不安全
package unsafe;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListTest {
/*
ArrayList 的一个线程安全的变体,其中所有可变操作(add、set 等等)都是通过对底层数组进行一次新的复制来实现的。
CopyOnWriteArrayList
public CopyOnWriteArrayList(Collection<? extends E> c)
创建一个按 collection 的迭代器返回元素的顺序包含指定 collection 元素的列表。
*/
public static void main(String[] args) {
//并发下ArrayList是不安全的
/**
* 解决方案:
* 1.方案1、List<String> list = new Vector<>();
* 2.List<String> list = Collections.synchronizedList(Arrays.asList("1", "2", "3"));
* 3.List<String> list = new CopyOnWriteArrayList<>();
*/
/** CopyOnWriteArrayList 写入时赋值 COW 计算机程序设计领域的一种优化策略;
* uoge线程调用时,list读取的时候,固定的,写入(覆盖)
* 在写入的时候避免覆盖,造成数据问题
* 读写分离
* CopyOnWriteArrayList 比 Vector 好在哪里?
* 写入的时候复制一份
*/
List<String> list = new CopyOnWriteArrayList<>();
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();
}
}
}
源码:写入的时候复制一份
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xg42kdgZ-1634039720370)(C:/Users/77/AppData/Roaming/Typora/typora-user-images/image-20211007101311179.png)]
Set不安全
package unsafe;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
public class SetTest {
//java.util.ConcurrentModificationException 并发修改异常
public static void main(String[] args) {
/*
解决方案
1.Set<String> set = Collections.synchronizedSet(new HashSet<>());
2.CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
*/
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
for (int i =1; i <=10 ;i ++){
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashSet底层是什么?
可以看出 HashSet 的底层就是一个HashMap
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}//add set 本质就是map 的 key 是无法重复的
private static final Object PRESENT = new Object();//这是一个不变的值
Map不安全
回顾map的基本操作:
package unsafe;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class HashMapTest {
public static void main(String[] args) {
//map是这样用的么? 不是,工作中不用HashMap
//默认等价于什么? new HashMap<>(16,0.75)
//Map<String,String> map = new HashMap<>();//线程不安全
//加载因子、初始化容量
Map<String,String> map = new ConcurrentHashMap<>();//安全
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();
}
}
}
8.Callable (简单)
1.可以有返回值
2.可以抛出异常
3.方法不同
Callable 和 Runable 对比
例:比如Callable 是你自己,你想通过你的女朋友 **Runable **认识她的闺蜜 Thread
- Callable 是 java.util 包下 concurrent 下的接口,有返回值,可以抛出被检查的异常
- Runable 是 java.lang 包下的接口,没有返回值,不可以抛出被检查的异常
- 二者调用的方法不同,run()/ call()
同样的 Lock 和 Synchronized 二者的区别,前者是java.util 下的接口 后者是 java.lang 下的关键字。
如何使用Callable?
package callable;
import demo02.C;
import sun.awt.windows.ThemeReader;
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 MyThread()).start();
//new Thread(new FutureTask<>(Callable)).strat();
//线程启动的方式
//new 一个对象
MyThread myThread = new MyThread();
//适配类,使Callable可以被调用
FutureTask futureTask = new FutureTask<>(myThread);
new Thread(futureTask,"A").start();
//两个对象会调用几个call
//一个,结果会被缓存,提高效率,因此只打印一个call
new Thread(futureTask,"B").start();
Integer integer = (Integer)futureTask.get();//获取Callable的返回结果 // get方法可能会产生阻塞,把它放到最后,后者通过异步通信
System.out.println(integer);
}
}
/*
class MyThread implements Runnable{
@Override
public void run() {
}
}*/
//<String> 代表所需要的返回值
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("call()");
return 1024;
}
}
细节:
1、有缓存
2、结果可能需要等待,会阻塞!
9.常用的辅助类(必会)
CountDownLatch
减法计数器: 实现调用几次线程后 再触发某一个任务
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
package add;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import java.util.concurrent.CountDownLatch;
//计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//倒计时 总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);
countDownLatch.countDown(); //-1
for (int i =1; i<=6 ; i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "GO out");
countDownLatch.countDown();//-1
},String.valueOf(i)).start();
}
countDownLatch.await(); // 等待计数器归零,然后再向下执行
System.out.println("close door");
}
}
1GO out
6GO out
4GO out
3GO out
5GO out
2GO out
close door
countDownLatch.countDown();
// 数量-1
countDownLatch.await();
// 等待计数器归零,然后再向下执行
每次有线程调用 countDown() 数量-1,假设计数器变为0,countDownLatch.await() 就会被唤醒,继续执行!
CyclicBarrier
加法计数器
package 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("success");
});
for (int i = 0; i<7;i++){
final int temp = i;
//lamdba能操作到i嘛
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "收集" + temp + "个龙珠");
try{
cyclicBarrier.await();//等待
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
Thread-0收集0个龙珠
Thread-5收集5个龙珠
Thread-4收集4个龙珠
Thread-2收集2个龙珠
Thread-1收集1个龙珠
Thread-3收集3个龙珠
Thread-6收集6个龙珠
success
Semaphore
Semaphore:信号量
限流/抢车位!6车—3个停车位置
package 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 =0 ;i<6;i++){
new Thread(()->{
try {
//acquire 获得
//release 释放
semaphore.acquire();//获得
System.out.println(Thread.currentThread().getName()+ "抢到车位");
TimeUnit.SECONDS.sleep(2);//停2秒
//离开车位
System.out.println(Thread.currentThread().getName() + "离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
0抢到车位
3抢到车位
1抢到车位
1离开车位
0离开车位
3离开车位
5抢到车位
2抢到车位
4抢到车位
5离开车位
2离开车位
4离开车位
Process finished with exit code 0
semaphore.acquire();
获得,假设如果已经满了,等待,等待被释放为止!
semaphore.release();
释放,会将当前的信号量释放 + 1,然后唤醒等待的线程!
作用: 多个共享资源互斥的使用!并发限流,控制最大的线程数!
10.读写锁 ReadWriteLock
自定义的缓存,没有加锁,就会出现一个没有写入完成,另一个突然插进来的情况
package add;
import java.util.HashMap;
import java.util.Map;
/**
* ReadWriteLock
*/
public class ReadWriteLock {
public static void main(String[] args) {
MyCache myCache = new MyCache();
//写入
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 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);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取OK");
};
}
2写入2
5写入5
5写入OK
4写入4
4写入OK
3写入3
1写入1
3写入OK
2写入OK
2读取2
1读取1
1写入OK
1读取OK
2读取OK
3读取3
5读取5
5读取OK
4读取4
4读取OK
3读取OK
Process finished with exit code 0
使用读写锁
package add;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 独占锁(写锁) 一次只能被一个线程占用
* 共享锁(读锁) 多个线程可以同时占有
* ReadWriteLock
* 读- 读 可以共存
* 读- 写 不能共存
* 写- 写 不能共存
*
*/
public class ReadWriteLock {
public static void main(String[] args) {
MyCacheLock myCacheLock = new MyCacheLock();
//写入
for (int i = 1; i<= 5; i++){
final int temp = i;
new Thread(() -> {
myCacheLock.put(temp+"",temp+"");
},String.valueOf(i)).start();
}
//读取
for (int i = 1; i<= 5; i++){
final int temp = i;
new Thread(() -> {
myCacheLock.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);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取OK");
};
}
//加锁的缓存
class MyCacheLock{
private volatile Map<String,Object> map = new HashMap<>();
private ReentrantReadWriteLock 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() + "写入OK");
}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() + "读取OK");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.readLock().unlock();
}
};
}
1写入1
1写入OK
2写入2
2写入OK
3写入3
3写入OK
4写入4
4写入OK
5写入5
5写入OK
1读取1
1读取OK
3读取3
3读取OK
2读取2
2读取OK
5读取5
4读取4
4读取OK
5读取OK
11.阻塞队列
阻塞队列:
BlockingQueue 是不一个新东西
什么情况下我们会使用阻塞队列:多线程并发,线程池使用的较多
学会使用队列
添加移除
四组API
方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞 等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer() | put() | offer(,) |
移除 | remove | poll() | take() | poll(,) |
检测队首元素 | element | peek() | - | - |
抛出异常的
package queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Test {
//Collection
//list
//Set
public static void main(String[] args) {
test1();
}
/**
* 抛出异常
*/
public static void test1(){
//队列的大小
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(arrayBlockingQueue.add("A"));
System.out.println(arrayBlockingQueue.add("B"));
System.out.println(arrayBlockingQueue.add("C"));
//IllegalStateException 抛出异常
//System.out.println(arrayBlockingQueue.add("D"));
System.out.println("---------------");
System.out.println(arrayBlockingQueue.element());//查看队首的元素
System.out.println("---------------");
System.out.println(arrayBlockingQueue.remove());//谁先进谁先出
System.out.println(arrayBlockingQueue.remove());
System.out.println(arrayBlockingQueue.remove());
//NoSuchElementException
//System.out.println(arrayBlockingQueue.remove());
}
}
有返回值也不抛出异常
package queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Test {
//Collection
//list
//Set
public static void main(String[] args) {
test2();
}
public static void test2(){
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(3);
System.out.println(arrayBlockingQueue.offer("A"));
System.out.println(arrayBlockingQueue.offer("B"));
System.out.println(arrayBlockingQueue.offer("C"));//true
System.out.println("-----------------");
System.out.println(arrayBlockingQueue.peek());
//System.out.println(arrayBlockingQueue.offer("D"));//false 不抛出异常 返回一个boolean值
System.out.println("-----------------");
System.out.println(arrayBlockingQueue.poll());
System.out.println(arrayBlockingQueue.poll());
System.out.println(arrayBlockingQueue.poll());//依旧是先进先出
System.out.println(arrayBlockingQueue.poll());//None 也不抛出异常
}
}
等待一直阻塞
package queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Test {
//Collection
//list
//Set
public static void main(String[] args) {
try {
test3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 等待,阻塞(一直阻塞)
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue =new ArrayBlockingQueue(3);
//一直阻塞
arrayBlockingQueue.put("A");
arrayBlockingQueue.put("B");
arrayBlockingQueue.put("C");
//arrayBlockingQueue.put("D");//队列没有位置了,他会一直等待
System.out.println("----------------");
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
//System.out.println(arrayBlockingQueue.take());
}
}
超时等待
package queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Test {
//Collection
//list
//Set
public static void main(String[] args) {
try {
test4();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 抛出异常
*/
public static void test1(){
//队列的大小
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(arrayBlockingQueue.add("A"));
System.out.println(arrayBlockingQueue.add("B"));
System.out.println(arrayBlockingQueue.add("C"));
//IllegalStateException 抛出异常
//System.out.println(arrayBlockingQueue.add("D"));
System.out.println("---------------");
System.out.println(arrayBlockingQueue.element());//查看队首的元素
System.out.println("---------------");
System.out.println(arrayBlockingQueue.remove());//谁先进谁先出
System.out.println(arrayBlockingQueue.remove());
System.out.println(arrayBlockingQueue.remove());
//NoSuchElementException
//System.out.println(arrayBlockingQueue.remove());
}
/**
* 不抛出异常
*/
public static void test2(){
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(3);
System.out.println(arrayBlockingQueue.offer("A"));
System.out.println(arrayBlockingQueue.offer("B"));
System.out.println(arrayBlockingQueue.offer("C"));//true
System.out.println("-----------------");
System.out.println(arrayBlockingQueue.peek());
//System.out.println(arrayBlockingQueue.offer("D"));//false 不抛出异常 返回一个boolean值
System.out.println("-----------------");
System.out.println(arrayBlockingQueue.poll());
System.out.println(arrayBlockingQueue.poll());
System.out.println(arrayBlockingQueue.poll());//依旧是先进先出
System.out.println(arrayBlockingQueue.poll());//None 也不抛出异常
}
/**
* 等待,阻塞(一直阻塞)
*/
public static void test3() throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue =new ArrayBlockingQueue(3);
//一直阻塞
arrayBlockingQueue.put("A");
arrayBlockingQueue.put("B");
arrayBlockingQueue.put("C");
//arrayBlockingQueue.put("D");//队列没有位置了,他会一直等待
System.out.println("----------------");
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
System.out.println(arrayBlockingQueue.take());
//System.out.println(arrayBlockingQueue.take());
}
/**
* 等待,(超时)
*/
public static void test4() throws InterruptedException {
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(3);
arrayBlockingQueue.offer("a");
arrayBlockingQueue.offer("b");
arrayBlockingQueue.offer("c");
//arrayBlockingQueue.offer("d", 2,TimeUnit.SECONDS);//超时等待两秒
arrayBlockingQueue.poll();
arrayBlockingQueue.poll();
arrayBlockingQueue.poll();
arrayBlockingQueue.poll(2,TimeUnit.SECONDS);
}
}
SynchronousQueue 同步队列
没有容量,进去一个元素,必须等待取出来之后,才能再往里面放一个元素!
package queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
* 同步队列
* 和其他的BlockingQueue不一样,SynchronousQueue 不存储元素
* put了一个元素,必须先take取出来,否则不能取出值
*/
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingDeque = new SynchronousQueue<>();//同步队列
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + "PUT 1");
blockingDeque.put("1");
System.out.println(Thread.currentThread().getName() + "PUT 2");
blockingDeque.put("2");
System.out.println(Thread.currentThread().getName() + "PUT 3");
blockingDeque.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" + blockingDeque.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" + blockingDeque.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "=>" +blockingDeque.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T2").start();
}
}
T1PUT 1
T21
T1PUT 2
T22
T1PUT 3
T23
12.线程池
线程池:3大方法、7大参数、4种拒绝策略
池化技术
程序的运行,本质:占用系统的资源!优化资源的使用! ==> 引进了一种技术池化池
线程池、连接池、内存池、对象池…
池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我。
线程池的好处
1.降低资源的小号
2.提高响应的速度
3.方便管理
线程可以复用、可以控制最大并发数、管理线程
线程池的三大方法
单个线程
package pool;
import sun.awt.windows.ThemeReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors 工具类 三大方法
//使用了线程池之后,要使用线程池创建线程
public class Test01 {
public static void main(String[] args) {
ExecutorService threadpool = Executors.newSingleThreadExecutor();//单个线程
//Executors.newFixedThreadPool(5);//创建一个固定的线程池的大小
//Executors.newCachedThreadPool();//可伸缩的缓存
try{
for(int i =1;i < 10; i++){
//使用了线程池之后,使用线程池来创建线程
threadpool.execute(()->{
System.out.println(Thread.currentThread().getName() + "-OK" );
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
//程序结束要停止线程池
threadpool.shutdown();
}
}
}
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
pool-1-thread-1-OK
Process finished with exit code 0
创建一个固定先线程池的大小
这里最多有五个线程同时执行
package pool;
import sun.awt.windows.ThemeReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors 工具类 三大方法
//使用了线程池之后,要使用线程池创建线程
public class Test01 {
public static void main(String[] args) {
//ExecutorService threadpool = Executors.newSingleThreadExecutor();//单个线程
ExecutorService threadpool = Executors.newFixedThreadPool(5);//创建一个固定的线程池的大小
//Executors.newCachedThreadPool();//可伸缩的缓存
try{
for(int i =1;i < 10; i++){
//使用了线程池之后,使用线程池来创建线程
threadpool.execute(()->{
System.out.println(Thread.currentThread().getName() + "-OK" );
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
//程序结束要停止线程池
threadpool.shutdown();
}
}
}
pool-1-thread-1-OK
pool-1-thread-4-OK
pool-1-thread-3-OK
pool-1-thread-2-OK
pool-1-thread-4-OK
pool-1-thread-3-OK
pool-1-thread-5-OK
pool-1-thread-1-OK
pool-1-thread-2-OK
缓存可伸缩的线程池
最多可以十个线程同时执行
package pool;
import sun.awt.windows.ThemeReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors 工具类 三大方法
//使用了线程池之后,要使用线程池创建线程
public class Test01 {
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();
}
}
}
pool-1-thread-1-OK
pool-1-thread-4-OK
pool-1-thread-7-OK
pool-1-thread-5-OK
pool-1-thread-2-OK
pool-1-thread-6-OK
pool-1-thread-8-OK
pool-1-thread-9-OK
pool-1-thread-10-OK
pool-1-thread-3-OK
7大参数
源码分析
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
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) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
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;
}
手动创建一个线程池
package pool;
import sun.awt.windows.ThemeReader;
import java.util.concurrent.*;
//Executors 工具类 三大方法
//使用了线程池之后,要使用线程池创建线程
public class Test01 {
public static void main(String[] args) {
//自定义线程池
ExecutorService threadpool = new ThreadPoolExecutor(2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),//阻塞队列三个
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());//银行满了,但是还有人进来,不处理这个人,并抛出异常
try{
//最大的承载 队列的值+max的值
//RejectedExecutionException 拒绝策略,超出最大承载
for(int i =0;i <6; 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()
* 队列满了,尝试去和最早的竞争,如果竞争失败的话,也不会抛出异常!
*/
最大线程到底如何定义
池的最大大小如何去设置
1.CPU密集型
几核的CPU就定义为几,可以保存CPU的性能最高
2.IO密集型
判断你程序中十分耗IO的线程,
程序有15个大型任务,IO十分占用资源, IO密集型参数(最大线程数)就设置为大于15即可,一般选择两倍
13.四大函数式接口(必须掌握)
新时代程序员:lambda表达式、链式编程、函数式接口、Stream流式计算
函数接口:只有一个方法的接口
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
//超级多@FunctionalInterface
//减缓编程模型,在新版本中的框架底层大量应用
//foreach(消费者类型的函数式接口)
四大函数式接口
Function函数式接口
package function;
import java.util.function.Function;
/**
* Function 函数型接口
* 只要是函数结构就可以用lambda简化
*/
public class demo01 {
public static void main(String[] args) {
//工具类:输出输入的值
/*Function function = new Function<String,String>() {
@Override
public String apply(String o) {
return o;
}
};
System.out.println(function.apply("asd"));*/
Function<String,String> function = (str) ->{return str;};
System.out.println(function.apply("ads"));
}
}
Predicate 断定型接口
断定型接口:有一个输入参数,返回值只能是 布尔值!
package function;
import java.util.function.Predicate;
/*
断定型接口:有一个输入参数,返回值只能是boolean值
*/
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(""));//true
System.out.println(predicate.test("1"));//false
}
}
Consumer 消费型接口
package 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 s) {
System.out.println(s);
}
};*/
Consumer<String> consumer = (str) -> {
System.out.println(str);
};
consumer.accept("asb");
}
}
Supplier 供给型接口
package function;
import java.util.function.Supplier;
/*
supplier 供给型接口,不需要输入只有返回值
*/
public class demo04 {
public static void main(String[] args) {
/* Supplier supplier = new Supplier<Integer>(){
@Override
public Integer get() {
System.out.println("get()");
return 1024;
}
};*/
Supplier<Integer> supplier = () -> {return 1024;};
System.out.println(supplier.get());
}
}
14.Stream 流式计算(建议自己查找一些资料深入理解方法)
什么是Stream流式计算
大数据:存储+计算
集合、Mysql本质就是用来存东西
计算都应该交给流来操作
package stream;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* 题目要求:一分钟完成此题,只能用一行代码解决
* 现在有五个用户!筛选:
* 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> users = Arrays.asList(u1, u2, u3, u4, u5);
//计算交给流
//链式编程
users.stream()
.filter(u->{return u.getId()%2==0;})//判断偶数
.filter(u ->{return u.getAge() >23;})//判断大于23岁
.map(u -> {return u.getName().toUpperCase(Locale.ROOT);})//名字大写
//.sorted((uu1,uu2)->{return uu1.compareTo(uu2);})//正序
.sorted((uu1,uu2)->{return uu2.compareTo(uu1);})//倒叙
.limit(1)
.forEach(System.out::println);
}
}
class User{
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
15.ForkJoin(建议自己查找一些资料深入理解方法)
什么是 ForkJoin
ForkJoin 在 JDK 1.7 , 并行执行任务!提高效率。大数据量!
大数据:Map Reduce (把大任务拆分为小任务)
ForkJoin 特点:工作窃取
这个里面维护的都是双端队列
ForkJoin
通过forkjoinPool来执行forkjoin
接口
构造方法
使用forkjoin
如何使用frokjoin
- 1.forkjoinPool通过它来执行
- 2.计算任务forkjoinPool.execute(ForkJoinTask task)
- 3.计算类要继承RecursiveTask(递归任务有返回值)
package forkJoin;
import java.util.concurrent.RecursiveTask;
/**
* 求和计算的任务
* 3000 6000(frokjoin) 9000(Stream并行流)
* 如何使用frokjoin
* 1.forkjoinPool通过它来执行
* 2.计算任务forkjoinPool.execute(ForkJoinTask task)
* 3.计算类要继承RecursiveTask(递归任务有返回值)
*/
public class ForkJoinDemo extends RecursiveTask<Long> {
private Long start;
private Long end;
//临界值
private Long temp = 10000L;
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+=i;
}
return sum;
}else {
//forkjoin 递归
long middle = (start + end) /2; //中间值
ForkJoinDemo task1 = new ForkJoinDemo(start,middle);
task1.fork();//拆分任务,把任务压入线程队列
ForkJoinDemo task2 = new ForkJoinDemo(middle,end);
task2.fork();
return task1.join() + task2.join();
}
}
}
package forkJoin;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class Test {
public static void main(String[] args) {
test1();//4391
try {
test2();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
test3();
}
public static void test1(){
Long sum = 0L;
long start = System.currentTimeMillis();
for (long i =1L;i<=10_0000_0000;i++){
sum +=i;
}
long end = System.currentTimeMillis();
System.out.println("sum = " + sum + "时间:" + (end - start));
}
public static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(0L,10_0000_0000L); //向下转型
ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务
Long sum = submit.get();//获得结果
long end = System.currentTimeMillis();
System.out.println("sum=" + sum +"时间:" + (end - start));
}
public static void test3(){
long start = System.currentTimeMillis();
//stream并行流
Long sum = LongStream.rangeClosed(0L, 10_0000_0000L)
.parallel()//并行计算
.reduce(0,Long::sum);//调用Long下面的sum方法 输出结果
long end = System.currentTimeMillis();
System.out.println("sum =" + sum + "时间:" + (end - start));
}
}
sum = 500000000500000000时间:6183
sum=500065535999828224时间:4775
sum =500000000500000000时间:154
16.异步回调
同步回调
我们常用的一些请求都是同步回调的,同步回调是阻塞的,单个的线程需要等待结果的返回才能继续执行。
异步回调
有的时候,我们不希望程序在某个执行方法上一直阻塞,需要先执行后续的方法,那就是这里的异步回调。我们在调用一个方法时,如果执行时间比较长,我们可以传入一个回调的方法,当方法执行完时,让被调用者执行给定的回调方法。
Future 设计的初衷: 对将来的某个事件的结果进行建模
package future;
import demo02.C;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* 异步调用:CompletableFuture
* 异步执行
* 成功回调
* 失败回调
*/
public class Demo01 {
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");
});
System.out.println("11111");
completableFuture.get();//获取执行结果
*/
//有返回值的异步回调
//Ajax 成功和失败的回调
//返回的是错误信息
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(()->{
System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
//int i = 10/0;
return 1024;
});
System.out.println(completableFuture.whenComplete((t,u)->{//成功的时候返回
//成功的时候t为1024 u为null
System.out.println("t=>" + t);//错的是时候 null
System.out.println("u=>" + u);//发生错误就打印 java.lang.ArithmeticException: / by zero
//java.util.concurrent.CompletionException:
//java.lang.ArithmeticException: / by zero
}).exceptionally((e)->{//失败的时候返回
System.out.println(e.getMessage());
return 2333;
}).get());
/**
* sucess code 200
* erroe code 404 500
*/
}
}
17.JMM
请你谈谈你对 Volatile 的理解
Volatile 是 Java 虚拟机提供轻量级的同步机制,类似于synchronized 但是没有其强大。
1.保证可见性
2.不保证原子性
3.防止指令重排
什么是JMM
JMM : Java内存模型,不存在的东西,概念!约定!
关于JMM的同步约定:
1.线程解锁前,必须把共享变量立刻刷回主存
2.线程加锁前,必须读取主存中的最新值到工作内存中!
3.加锁和解锁是同一把锁
线程 :工作内存
、主内存
内存划分
JMM规定了内存主要划分为主内存和工作内存两种。此处的主内存和工作内存跟JVM内存划分(堆、栈、方法区)是在不同的层次上进行的,如果非要对应起来,主内存对应的是Java堆中的对象实例部分,工作内存对应的是栈中的部分区域,从更底层的来说,主内存对应的是硬件的物理内存,工作内存对应的是寄存器和高速缓存。
JVM在设计时候考虑到,如果JAVA线程每次读取和写入变量都直接操作主内存,对性能影响比较大,所以每条线程拥有各自的工作内存,工作内存中的变量是主内存中的一份拷贝,线程对变量的读取和写入,直接在工作内存中操作,而不能直接去操作主内存中的变量。但是这样就会出现一个问题,当一个线程修改了自己工作内存中变量,对其他线程是不可见的,会导致线程不安全的问题。因为JMM制定了一套标准来保证开发者在编写多线程程序的时候,能够控制什么时候内存会被同步给其他线程。
8种操作
内存交互操作有8种,虚拟机实现必须保证每一个操作都是原子的,不可在分的(对于double和long类型的变量来说,load、store、read和write操作在某些平台上允许例外)
-
lock (锁定):作用于主内存的变量,把一个变量标识为线程独占状态
-
unlock (解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
-
read (读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
-
load (载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
-
use (使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
-
assign (赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
-
store (存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
-
write (写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
JMM对这八种指令的使用,制定了如下规则:
-
不允许read和load、store和write操作之一单独出现。即使用了read必须load,使用了store必须write
-
不允许线程丢弃他最近的assign操作,即工作变量的数据改变了之后,必须告知主存
-
不允许一个线程将没有assign的数据从工作内存同步回主内存
-
一个新的变量必须在主内存中诞生,不允许工作内存直接使用一个未被初始化的变量。就是怼变量实施use、store操作之前,必须经过assign和load操作
-
一个变量同一时间只有一个线程能对其进行lock。多次lock后,必须执行相同次数的unlock才能解锁
-
如果对一个变量进行lock操作,会清空所有工作内存中此变量的值,在执行引擎使用这个变量前,必须重新load或assign操作初始化变量的值
-
如果一个变量没有被lock,就不能对其进行unlock操作。也不能unlock一个被其他线程锁住的变量
-
对一个变量进行unlock操作之前,必须把此变量同步回主内存
JMM对这八种操作规则和对volatile的一些特殊规则就能确定哪里操作是线程安全,哪些操作是线程不安全的了。但是这些规则实在复杂,很难在实践中直接分析。所以一般我们也不会通过上述规则进行分析。更多的时候,使用java的happen-before规则来进行分析。
问题:程序不知道主内存的值已经被修改过了
package volatileT;
import java.util.concurrent.TimeUnit;
public class JMMDemo {
private static int num = 0;
public static void main(String[] args) {
new Thread(()->{//线程1
while(num == 0){
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
18.Volatile
1.保证可见性
package volatileT;
import java.util.concurrent.TimeUnit;
public class JMMDemo {
//不加 volatile程序就会死循环!
//加了 volatile可以保证可见性
private volatile static int num = 0;
public static void main(String[] args) {
new Thread(()->{//线程1 对主内存的变化不知道的
while(num == 0){
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num = 1;
System.out.println(num);
}
}
2.不保证原子性
原子性:不可分割
线程A在执行任务的时候,不能被打扰的,也不能被分割。要么同时成功,要么同时失败
package volatileT;
//不保证原子性
public class VDemo02 {
private volatile static int num = 0;
/*public synchronized static void add(){
num++;
}//200000*/
public static void add(){
num++;
}
//理论上num结果为2w
public static void main(String[] args) {
for (int i =1;i<=20;i++){
new Thread(()->{
for (int j=0;j<1000;j++){
add();
}
}).start();
}
while(Thread.activeCount()>2){
//java中有两个线程是默认执行的一个是main一个GC
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + " " + num);
}
}
如果不加lock和synchronized,怎么样保证原子性
使用原子类来解决原子性问题
package volatileT;
import java.util.concurrent.atomic.AtomicInteger;
//不保证原子性
public class VDemo02 {
//原子类的Integer
private volatile static AtomicInteger num = new AtomicInteger();
/*public synchronized static void add(){
num++;
}//200000*/
public static void add(){
//num++;//不是一个原子性操作
num.getAndIncrement();//+1方法 用底层的CAS
}
//理论上num结果为2w
public static void main(String[] args) {
for (int i =1;i<=20;i++){
new Thread(()->{
for (int j=0;j<1000;j++){
add();
}
}).start();
}
while(Thread.activeCount()>2){
//java中有两个线程是默认执行的一个是main一个GC
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + " " + num);
}
}
这些类的底层都直接和操作系统挂钩!在内存中修改值!Unsafe类是一个很特殊的存在!
3.禁止指令重排
指令重排
什么是指令重排?:我们写的程序,计算机并不是按照你写的那样去执行的。
源代码 —> 编译器优化的重排 —> 指令并行也可能会重排 —> 内存系统也会重排 ——> 执行
处理器在执行指令重排的时候,会考虑:数据之间的依赖性
int x = 1; // 1
int y = 2; // 2
x = x + 5; // 3
y = x * x; // 4
我们所期望的:1234 但是可能执行的时候会变成 2134 或者 1324,但是不可能是 4123!
前提:a b x y 这四个值默认都是 0:
可能造成影响得到不同的结果:
线程A | 线程B |
---|---|
x = a | y = b |
b =1 | a = 2 |
正常的结果:x = 0,y = 0;
但是由于指定重排可能执行顺序发生变化,出现以下结果:
线程A | 线程B |
---|---|
b = 1 | a = 2 |
x = a | y = b |
指令重排导致的异常结果:x = 2,y= 1;
volatile 可以避免指令重排:
内存屏障是一个CPU指令。作用:
1.保持特定操作的执行顺序!
2.可以保证某些变量的内存可见性(利用volatile实现了可见性)
Volatile是可以保持可见性,不能保证原子性,由于内存屏障,可以保证避免指令重排的现象产生!
volatile 内存屏障在单例模式中使用的最多!
19.单例模式
饿汉式DCL懒汉式,深究
什么是单例模式
java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例、饿汉式单例
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。
单例模式有以下特点:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
饿汉式
//饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton1 {
private Singleton1() {}
private static final Singleton1 single = new Singleton1();
//静态工厂方法
public static Singleton1 getInstance() {
return single;
}
}
饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的。
package single;
//饿汉式单例
public class Hungry {
//可能会浪费空间
//把所有的对象全部加载进来
private byte[] date1 = new byte[1024*1024];
private byte[] date2 = new byte[1024*1024];
private byte[] date3 = new byte[1024*1024];
private byte[] date4 = new byte[1024*1024];
private Hungry(){
}
//在类创建的时候就已经创建好了一个静态对象提供使用
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance(){
return HUNGRY;
}
}
懒汉式
//懒汉式单例类.在第一次调用的时候实例化自己
public class Singleton {
private Singleton() {}
private static Singleton single=null;
//静态工厂方法
public static Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
}
package single;
//懒汉式单例模式
public class LazyMan {
public LazyMan() {
System.out.println(Thread.currentThread().getName() + "ok" );
}
private volatile static LazyMan lazyMan;//lazyMan必须加上volatile防止指令重排
public static LazyMan getInstance(){
//加锁
//双重检测锁模式
if (lazyMan == null){
synchronized (LazyMan.class){//只有在空的时候才开始抢锁
if (lazyMan == null) {
lazyMan = new LazyMan();//不是一个原子性操作
/**
* 1.分配内存空间
* 2.执行构造方法,初始化对象
* 3.把这个对象指向这个空间
*
* 期望顺序是:123
* 特殊情况下实际执行:132 ===> 此时 A 线程没有问题
* 若额外加一个 B 线程
* 此时lazyMan还没有完成构造
*/
}
}
}
return lazyMan;
}
//单线程下是可以的
//多线程并发
//线程启动偶尔成功,偶尔失败
public static void main(String[] args) {
for (int i =0;i<10;i++){
new Thread(()->{
LazyMan.getInstance();
}).start();
}
}
}
LazyMan通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,LazyMan的唯一实例只能通过getInstance()方法访问。
但是以上懒汉式单例的实现没有考虑线程安全问题,它是线程不安全的,并发环境下很可能出现多个LazyMan实例,要实现线程安全,需要对getInstance这个方法进行改造。上述方式使用了双重检查锁定,下面的方法使用了静态内部类
既实现了线程安全,又避免了同步带来的性能影响。
public class Singleton {
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
反射来破坏单例模式
package single;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
//懒汉式单例模式
public class LazyMan {
private static boolean flag = false;//标志位
//解决方法,但是不彻底
public LazyMan() {
synchronized (LazyMan.class){
if (flag == false){
flag = true;
}else {
throw new RuntimeException("不要试图使用反射构造异常");
}
}
System.out.println(Thread.currentThread().getName() + "ok" );
}
private volatile static LazyMan lazyMan;//lazyMan必须加上volatile防止指令重排
public static LazyMan getInstance(){
//加锁
//双重检测锁模式
if (lazyMan == null){
synchronized (LazyMan.class){//只有在空的时候才开始抢锁
if (lazyMan == null) {
lazyMan = new LazyMan();//不是一个原子性操作
/**
* 1.分配内存空间
* 2.执行构造方法,初始化对象
* 3.把这个对象指向这个空间
*
* 期望顺序是:123
* 特殊情况下实际执行:132 ===> 此时 A 线程没有问题
* 若额外加一个 B 线程
* 此时lazyMan还没有完成构造
*/
}
}
}
return lazyMan;
}
//单线程下是可以的
//多线程并发
//线程启动偶尔成功,偶尔失败
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//反射 破坏了构造器
//LazyMan instance = LazyMan.getInstance();
Field flag = LazyMan.class.getDeclaredField("flag");
flag.setAccessible(true);
Constructor<LazyMan> declaredConstructors = LazyMan.class.getDeclaredConstructor(null);
declaredConstructors.setAccessible(true);
LazyMan instance = declaredConstructors.newInstance();
flag.set(instance,false);
LazyMan instance2 = declaredConstructors.newInstance();
System.out.println(instance);
System.out.println(instance2);
}
}
解决方式
public LazyMan() {
synchronized (LazyMan.class){
if (flag == false){
flag = true;
}else {
throw new RuntimeException("不要试图使用反射构造异常");
}
}
}
使用枚举解决反射的破坏
package single;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
//enum 是一个什么?
//本身可以是class类
public enum Enumsingle {
INSTANCE;
public Enumsingle getInstance(){
return INSTANCE;
}
}
class Test{
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Enumsingle instance = Enumsingle.INSTANCE;
Constructor<Enumsingle> declaredConstructor = Enumsingle.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
Enumsingle instance2 = declaredConstructor.newInstance();
//NoSuchMethodException: single.Enumsingle.<init>() 没有空参构造方法
//IllegalArgumentException: Cannot reflectively create enum objects 不能使用反射破坏
System.out.println(instance);
System.out.println(instance2);
}
}
20.深入理解CAS
什么是 CAS
大厂你必须要深入研究底层!有所突破! 修内功,操作系统,计算机网络原理
package cas;
import java.util.concurrent.atomic.AtomicInteger;
public class CASDemo {
//比较并交换
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);//原子类
/*
期望 更新
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
*/
//如果和期望的值相同就更新,CAS是CPU的并发原语
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get()); // 2021
System.out.println(atomicInteger.compareAndSet(2020, 20201));
System.out.println(atomicInteger.get());//2021
}
}
unsafe类
CAS : 比较当前工作内存中的值和主内存中的值,如果这个值是期望的,那么则执行操作!如果不是就一直循环!
缺点:
1.循环会耗时
2.一次性只能保证一个共享变量的原子性
3.存在ABA问题
CAS : ABA 问题(狸猫换太子)
package cas;
import java.util.concurrent.atomic.AtomicInteger;
public class CASDemo {
//比较并交换
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(2020);//原子类
/*
期望 更新
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
*/
//对我们写平时写的sql:乐观锁
//如果和期望的值相同就更新,CAS是CPU的并发原语
//*******捣乱的线程**********
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get()); // 2021
System.out.println(atomicInteger.compareAndSet(2021, 2020));
System.out.println(atomicInteger.get()); // 2021
//********期望的线程*********
System.out.println(atomicInteger.compareAndSet(2020, 2021));
System.out.println(atomicInteger.get());//2021
}
}
如何解决这个问题?原子引用
21.原子引用
带版本号的原子操作
package cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
public class CASDemo {
//比较并交换
public static void main(String[] args) {
//AtomicInteger atomicInteger = new AtomicInteger(2020);//原子类
//Integer 使用了对象缓存机制,默认范围是 -128 ~ 127 ,推荐使用静态工厂方法 valueOf 获取对象实例,而不是 new,因为 valueOf 使用缓存,而 new 一定会创建新的对象分配新的内存空间;
AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(2020,1);//初始值,版本号时间戳
new Thread(()->{
int stamp = atomicInteger.getStamp();//获得版本号
System.out.println("A = >" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//最后两个参数,拿到最新的版本号,把版本号+1
System.out.println(atomicInteger.compareAndSet(2020, 2022, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("A2 = >"+atomicInteger.getStamp());
//把这个值该回去
System.out.println(atomicInteger.compareAndSet(2022, 2020, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("A3 = >"+atomicInteger.getStamp());
},"a").start();
new Thread(()->{
int stamp = atomicInteger.getStamp();//获得版本号
System.out.println("B = >" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.compareAndSet(2020, 6666, stamp, stamp + 1));
System.out.println("b2 = >" +atomicInteger.getStamp());
},"b").start();
}
}
**注意:Integer 使用了对象缓存机制,默认范围是 -128 ~ 127 ,推荐使用静态工厂方法 valueOf 获取对象实例,而不是 new,因为 valueOf 使用缓存,而 new 一定会创建新的对象分配新的内存空间;**每一次的2020都是一个新的值
修改之后
package cas;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
public class CASDemo {
//比较并交换
public static void main(String[] args) {
//AtomicInteger atomicInteger = new AtomicInteger(2020);//原子类
//Integer 使用了对象缓存机制,默认范围是 -128 ~ 127 ,推荐使用静态工厂方法 valueOf 获取对象实例,而不是 new,因为 valueOf 使用缓存,而 new 一定会创建新的对象分配新的内存空间;
AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(11,1);//初始值,版本号时间戳
new Thread(()->{
int stamp = atomicInteger.getStamp();//获得版本号
System.out.println("A = >" + stamp);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//最后两个参数,拿到最新的版本号,把版本号+1
System.out.println(atomicInteger.compareAndSet(11, 22, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("A2 = >"+atomicInteger.getStamp());
//把这个值该回去
System.out.println(atomicInteger.compareAndSet(22, 11, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));
System.out.println("A3 = >"+atomicInteger.getStamp());
},"a").start();
new Thread(()->{
int stamp = atomicInteger.getStamp();//获得版本号
System.out.println("B = >" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.compareAndSet(11, 66, stamp, stamp + 1));
System.out.println("b2 = >" +atomicInteger.getStamp());
},"b").start();
}
}
22.各种锁的理解
1.公平锁、非公平锁
公平锁: 非常公平, 不能够插队,必须先来后到!
非公平锁:非常不公平,可以插队 (默认都是非公平)
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
2.可重入锁
递归锁
Synchroized
package lock;
//Synchorized
public class Demo01 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{
phone.sms();
},"a").start();
new Thread(()->{
phone.sms();
},"b").start();
}
}
class Phone{
public synchronized void sms(){
System.out.println(Thread.currentThread().getName() + "sms");
call(); 这里也有锁(sms锁 里面的call锁)
}
public synchronized void call(){
System.out.println(Thread.currentThread().getName() + "call");
}
}
Lock锁
package lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo02 {
public static void main(String[] args) {
Phone2 phone = new Phone2();
new Thread(()->{
phone.sms();
},"a").start();
new Thread(()->{
phone.sms();
},"b").start();
}
}
class Phone2{
Lock lock = new ReentrantLock();
public void sms(){
lock.lock();//细节问题 第一把锁
//lock锁必须配对否则就会死在里面
try {
System.out.println(Thread.currentThread().getName() + "sms");
call(); 这里也有锁(sms锁 里面的call锁)
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public synchronized void call(){
lock.lock();//第二把锁
try {
System.out.println(Thread.currentThread().getName() + "call");
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
3.自旋锁
spinlock
package lock;
import javax.swing.text.rtf.RTFEditorKit;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TestSpinlock {
public static void main(String[] args) {
/*ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
reentrantLock.unlock();*/
//底层的是自旋锁CAS实现的
SpinlockDemo spinlockDemo = new SpinlockDemo();
new Thread(()->{
spinlockDemo.mylock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
spinlockDemo.myunlock();
}
},"T1").start();
//T1获得锁,T2一直在自旋。T1解锁后,T2才获得锁结束自旋
new Thread(()->{
spinlockDemo.mylock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
spinlockDemo.myunlock();
}
},"T2").start();
}
}
4.死锁
死锁是什么?
死锁测试,怎么排除死锁:
package lock;
import single.LazyMan;
import java.util.concurrent.TimeUnit;
public class DeadlockDemo {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new MyThread(lockA,lockB),"T1").start();
new Thread(new MyThread(lockB,lockA),"T2").start();
}
}
class MyThread implements Runnable{
private String lockA;
private String lockB;
public MyThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA){
//lockA想拿B
System.out.println(Thread.currentThread().getName() + "lock"+ lockA + "=> get" + lockB);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
//B想拿A
System.out.println(Thread.currentThread().getName() + "lock" + lockB + "=> get" + lockA);
}
}
}
}
解决问题
1.使用jps定位进程号 jps-l
2.使用jstack
查看进程信息,进程号来找到死锁信息
面试、工作中!排查问题:
1.日志
2.堆栈信息