JUC
经过尚硅谷李贺飞老师的视频讲解 总结下来的笔记
volatile关键字-内存可见性
package com.zhangan.juc;
import org.junit.Test;
/**
* @Author: 张安
* @Date: 2021/5/25 21:04
* @Description: volatile 关键字
*/
/*
内存可见性问题
多个线程都有各自的缓存 对于共享数据的操作不可见
synchronized (threadDemo) {} 可以解决这个问题 但是效率很低
volatile关键字:当多个线程进行操作共享数据时,可以保证内存中的数据可见。
相较于synchronized是一种较为轻量级的同步策略。
注意:
1. volatile 不具备“互斥性”
2. volatile不能保证变量的“原子性”
*/
public class TestJUC {
@Test
public void name1() {
ThreadDemo threadDemo = new ThreadDemo();
Thread thread = new Thread(threadDemo);
thread.start();
while (true) {
if (threadDemo.isFlag()) {
System.out.println("-------------");
break;
}
}
}
}
class ThreadDemo implements Runnable {
private volatile static boolean flag = false;
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println("flag=>" + isFlag());
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
原子变量-CAS算法
package com.zhangan.juc;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author: 张安
* @Date: 2021/5/25 21:50
* @Description:
*/
/*
i++的原子性问题: i++的操作实际上分为三个步骤读-改-写”
原子变量: jdk1.5 后java.util.concurrent.atomic包下提供了常用的原子变量:
1. volatile保证内存可见性
2.CAS (Compare-And-Swap)算法保证数据的原子性
CAS算法是硬件对于并发操作共享数据的支持
CAS包含了三个操作数:
内存值v
预估值A
更新值B
当且仅当V ==A时,v =B。否则,将不散任何操作
*/
public class TestAtomic {
public static void main(String[] args) {
AtomicDemo atomicDemo = new AtomicDemo();
for (int i = 0; i < 10; i++) {
new Thread(atomicDemo).start();
}
}
}
class AtomicDemo implements Runnable {
// private int serialNumber = 0;
private AtomicInteger serialNumber = new AtomicInteger();
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getSerialNumber());
}
public int getSerialNumber() {
return serialNumber.getAndIncrement();
}
}
ConcurrentHashMap锁分段机制
Java 5.0在java.util.concurrent包中提供了多种并发容器类来改进同步容器的性能。
ConcurrentHashMap同步容器类是Java 5增加的一个线程安全的哈希表。对与多线程的操作,介于HashMap 与Hashtable之间。内部采用“锁分段”机制替代Hashtable的独占锁。进而提高性能。
此包还提供了设计用于多线程上下文中的 collection实现:
ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkipListSet、CopyOnWriteArrayList和 copyOnWriteArraySet。当期望许多线程访问一个给定collection时,ConcurrentHashMap通常优于同步的HashMap,
ConcurrentSkipListMap通常优于同步的TreeMap。当期望的读数和遍历远远大于列表的更新数时,copyOnWriteArrayList优于同步的ArrayList。
package com.zhangan.juc;
/**
* @Author: 张安
* @Date: 2021/5/25 23:02
* @Description:
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* CopyOnWriteArrayList/CopyOnWriteArraySet:"写入并复制"
*/
public class TestCopyOnWriteArrayList {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
for (int i = 0; i < 10; i++) {
new Thread(helloThread).start();
}
}
}
class HelloThread implements Runnable {
// private static List<String> list = Collections.synchronizedList(new ArrayList<>());
//CopyOnWriteArrayList "写入并复制" 适合并发迭代操作 不适合添加操作 效率低
//添加操作多时,效率低,因为每次添加时都会进行复制,开销非常的天。并发迭代操作多时可以选择。
private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
static {
list.add("AA");
list.add("BB");
list.add("CC");
list.add("DD");
}
@Override
public void run() {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("AA");
}
}
}
CountDownLatch闭锁
Java 5.0在java.util.concurrent包中提供了多种并发容器类来改进同步容器的性能。
CountDownLatch 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
闭锁可以延迟线程的进度直到其到达终止状态,闭锁可以用来确保某些活动直到其他活动都完成才继续执行:
- 确保某个计算在其需要的所有资源都被初始化之后才继续执行;
- 确保某个服务在其依赖的所有其他服务都已经启动之后才启动;
- 等待直到某个操作所有参与者都准备就绪再继续执行。
package com.zhangan.juc;
/**
* @Author: 张安
* @Date: 2021/5/25 23:22
* @Description:
*/
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
/**
* CountDownLatch 闭锁
* 在完成某些运算时,只有其他所有的运算全部完成,当前运算才继续执行
*/
public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(5);
LatchDemo ld = new LatchDemo(latch);
LocalDateTime start = LocalDateTime.now();
for (int i = 0; i < 5; i++) {
new Thread(ld).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(start, end);
System.out.println("花费时间为:" + duration.toMillis());
}
}
class LatchDemo implements Runnable {
private CountDownLatch latch;
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
synchronized (this){
try {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
//计数器 减一操作
latch.countDown();
}
}
}
}
实现 Callable接口
package com.zhangan.juc;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Author: 张安
* @Date: 2021/5/26 15:49
* @Description: 实现 Callable接口 创建执行线程的方式三
* <p>
* 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常
* 执行Callable方式,需要FutureTask 实现类的支持,用于接收运算结果。
*/
public class TestCallable {
public static void main(String[] args) {
CallableDemo callableDemo = new CallableDemo();
FutureTask<Integer> futureTask = new FutureTask<>(callableDemo);
new Thread(futureTask).start();
//接收线程运算后的结果
try {
Integer sum = futureTask.get();
System.out.println(sum);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class CallableDemo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
Lock同步锁
package com.zhangan.juc;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author: 张安
* @Date: 2021/5/26 16:03
* @Description:
*/
/*
一、用于解决多线程安全问题的方式:
synchronized: 隐式锁
1。同步代码块
2。同步方法
jdk,1.5后:
3。同步锁Lock
注意:是一个显示锁,需要通过lock()方法上锁,必须通过unlock()方法进行释放锁
*/
public class TestLock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(ticket, "一号窗口").start();
new Thread(ticket, "二号窗口").start();
new Thread(ticket, "三号窗口").start();
}
}
class Ticket implements Runnable {
private int tick = 1000;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();//上锁
try {
if (tick > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "完成售票 余票为:" + (--tick));
} else {
break;
}
} finally {
//必须写到finally 释放锁
lock.unlock();
}
}
}
}
Condition控制线程通信
-
Condition接口描述了可能会与锁有关联的条件变量。这些变量在用法上与使用Object.wait访问的隐式监视器类似,但提供了更强大的功能。需要特别指出的是,单个Lock可能与多个Condition对象关联。为了避免兼容性问题,Condition方法的名称与对应的Object版本中的不同。
-
在Condition对象中,与 wait、notify和 notifyAll方法对应的分别是await、signal和 signalAll。
-
Condition实例实质上被绑定到一个锁上。要为特定Lock 实例获得Condition实例,请使用其newCondition()方法。
package com.zhangan.juc;
/**
* @Author: 张安
* @Date: 2021/5/26 16:19
* @Description: 生产者消费者案例
*
*
* 为了避免虚假唤醒问题,应该总是使用在循环中 if改成while
*/
public class TestProductorAndConsumer {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Consumer consumer = new Consumer(clerk);
new Thread(productor, "生产者A").start();
new Thread(consumer, "消费者B").start();
new Thread(productor, "生产者C").start();
new Thread(consumer, "消费者D").start();
}
}
//店员
class Clerk {
//商品
private int product = 0;
//进货
public synchronized void get() {
//为了避免虚假唤醒问题,应该总是使用在循环中
while (product >= 1) {
System.out.println("产品已满 无法添加");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + (++product));
this.notifyAll();
}
//卖货
public synchronized void sale() {
//为了避免虚假唤醒问题,应该总是使用在循环中
while (product <= 0) {
System.out.println("缺货");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + (--product));
this.notifyAll();
}
}
class Productor implements Runnable {
private Clerk clerk;
public Productor(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
//0.2秒的延迟
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();
}
}
}
class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
package com.zhangan.juc.productorandcunsumer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author: 张安
* @Date: 2021/5/26 16:19
* @Description: 生产者消费者案例
* <p>
* <p>
* Condition控制线程通信
*/
public class TestProductorAndConsumer2 {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Consumer consumer = new Consumer(clerk);
new Thread(productor, "生产者A").start();
new Thread(consumer, "消费者B").start();
new Thread(productor, "生产者C").start();
new Thread(consumer, "消费者D").start();
}
}
//店员
class Clerk {
//商品
private int product = 0;
private Lock lock = new ReentrantLock();
//控制线程通信
private Condition condition = lock.newCondition();
//进货
public void get() {
lock.lock();
try {
//为了避免虚假唤醒问题,应该总是使用在循环中
while (product >= 1) {
System.out.println("产品已满 无法添加");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + (++product));
condition.signalAll();
} finally {
lock.unlock();
}
}
//卖货
public void sale() {
lock.lock();
try {
//为了避免虚假唤醒问题,应该总是使用在循环中
while (product <= 0) {
System.out.println("缺货");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + (--product));
condition.signalAll();
} finally {
lock.unlock();
}
}
}
class Productor implements Runnable {
private Clerk clerk;
public Productor(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
//0.2秒的延迟
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();
}
}
}
class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
线程八锁
package com.zhangan.juc;
/**
* @Author: 张安
* @Date: 2021/5/26 19:14
* @Description: 线程八锁
* <p>
* <p>
* 题目:判断打印的"one" or "two"?
* <p>
* synchronized -> one two
* Thread.sleep(3000) -> one two
* 加了一个three 不带synchronized -> three one two
* <p>
* <p>
* 线程八锁的关键:
* 1.非静态方法的锁默认为this
* <p>
* 2.静态方法的锁为对应的Class实例
* ②某一个时刻内,只能有一个线程持有锁,无论几个方法。
*/
/*
1。两个普通同步方法,两个线程,标准打印,打印? //one two
2。新增 Thread.sleep()给getOne() ,打印? //one two
3。新增普通方法 getThree() ,打印? //three one two
4。两个普通同步方法,两个 Number对象,打印? //two one
5。修改getOne()为静态同步方法,打印? //two one
6,修改两个方法均为静态同步方法,一个 Number对象? //one two
7。一个静态同步方法,一个非静态同步方法,两个 Number对象? //two one
8。两个静态同步方法,两个Number对象? //one two
*/
public class TestThread8Monitor {
public static void main(String[] args) {
Number number = new Number();
// Number number1 = new Number();
new Thread(number::getOne).start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// Number.getOne();
// }
// }).start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// Number.getTwo();
// }
// }).start();
new Thread(number::getTwo).start();
// new Thread(number1::getTwo).start();
// new Thread(number::getThree).start();
}
}
class Number {
public synchronized void getOne() {
try {
System.out.println(this);
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("one");
}
public synchronized void getTwo() {
System.out.println(this);
System.out.println(Thread.currentThread().getName());
System.out.println("two");
}
// public void getThree() {
// System.out.println("three");
// }
}
线程按序交替
package com.zhangan.juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author: 张安
* @Date: 2021/5/26 16:56
* @Description: 编写一个程序,开启3个线程,这三个线程的ID分别为A、B、C,
* 每个线程将自己的ID在屏幕上打印10遍,要求输出的结果必须按顺序显示。
* 如:ABCABCABC.....依次递归
*/
public class TestABCAlternate {
public static void main(String[] args) {
AlternateDemo alternateDemo = new AlternateDemo();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
alternateDemo.loopA(i);
}
}
}, "A").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
alternateDemo.loopB(i);
}
}
}, "B").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
alternateDemo.loopC(i);
System.out.println("==============");
}
}
}, "C").start();
}
}
class AlternateDemo {
//当前正在执行线程的标记
private int number = 1;
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
//totalLoop 第几轮
public void loopA(int totalLoop) {
lock.lock();
try {
//判断
if (number != 1) {
condition1.await();
}
//打印
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
}
//唤醒
number = 2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void loopB(int totalLoop) {
lock.lock();
try {
//判断
if (number != 2) {
condition2.await();
}
//打印
for (int i = 1; i <= 15; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
}
//唤醒
number = 3;
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void loopC(int totalLoop) {
lock.lock();
try {
//判断
if (number != 3) {
condition3.await();
}
//打印
for (int i = 1; i <= 20; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
}
//唤醒
number = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
ReadWriteLock读写锁
package com.zhangan.juc;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @Author: 张安
* @Date: 2021/5/26 17:23
* @Description: 读写锁ReadWriteLock
*
* 写写/读写需要“互斥”
* 读读不需要互斥
*/
public class TestReadWriteLock {
public static void main(String[] args) {
ReadWriteLockDemo rw = new ReadWriteLockDemo();
new Thread(new Runnable() {
@Override
public void run() {
rw.set((int) (Math.random() * 101));
}
}, "Write").start();
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
rw.get();
}
}).start();
}
}
}
class ReadWriteLockDemo {
private int number = 0;
private ReadWriteLock lock = new ReentrantReadWriteLock();
//读
public void get() {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + ":" + number);
} finally {
lock.readLock().unlock();
}
}
//写
public void set(int number) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName());
this.number = number;
} finally {
lock.writeLock().unlock();
}
}
}
线程池
package com.zhangan.juc;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Author: 张安
* @Date: 2021/5/26 19:43
* @Description: 线程池
* <p>
* <p>
* 一、线程池:提供了一个线程陈列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。
* <p>
*/
/*
二、线程池体系结构
java.util.concurrent.Executor :负责线程的使用与调度的根接口
| --ExecutorService子接口:线程池的主要接口
|--ThreadPoolExecutor线程池的实现类
|--scheduledExecutorService子接口:负责线程的调度
|--ScheduledThreadPoolExecutor :继承ThreadPoolExecutor,实现了ScheduledThreadPoolExecutor
*/
/**
* <p>
* <p>
* 三、工具类:Executors
* ExecutorService newFixedThreadPool() :创建固定大小的线程池
* ExecutorService newCachedThreadPool()∶缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
* ExecutorService newSingleThreadExecutor() :创建单个线程池。线程池中只有一个线程
* <p>
* ScheduledExecutorService newScheduledThreadPool():创建固定大小的线程,可以延迟或定时的执行任务。
*/
public class TestThreadPool {
public static void main(String[] args) {
//创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
ThreadPoodDemo tpd = new ThreadPoodDemo();
//为线程池中的线程分配任务
for (int i = 0; i < 10; i++) {
pool.submit(tpd);
}
//关闭线程池
pool.shutdown();
}
}
class ThreadPoodDemo implements Runnable {
private int i = 0;
@Override
public void run() {
while (i <= 100) {
System.out.println(Thread.currentThread().getName() + ":" + (i++));
}
}
}
线程调度
package com.zhangan.juc;
import java.util.Random;
import java.util.concurrent.*;
/**
* @Author: 张安
* @Date: 2021/5/26 20:11
* @Description: 线程调度
*/
public class TestScheduledPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 10; i++) {
ScheduledFuture<Integer> result = pool.schedule(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int i = new Random().nextInt(100);
System.out.println(Thread.currentThread().getName() + ":" + i);
return i;
}
}, 1, TimeUnit.SECONDS);//延迟3秒
System.out.println(result.get());
}
pool.shutdown();
}
}