目录
什么是JUC
JUC 就是 java.util.concurrent
下面的类包,专门用于多线程的开发。
Lock:可重入锁、可重入读锁、可重入写锁
线程和进程
Java默认有几个线程?
答:2个线程。 main线程、GC线程
Java 真的可以开启线程吗?
答:开不了。Java 是没有权限去开启线程、操作硬件的,这是一个 native 的一个本地方法,它调用的底层的 C++ 代码。
// Thread类源码
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();
线程的状态有哪几种?
// Thread类源码
public enum State {
//新生
NEW,
//运行
RUNNABLE,
//阻塞
BLOCKED,
//等待
WAITING,
//超时等待
TIMED_WAITING,
//终止
TERMINATED;
}
并发:多线程操作同一个资源。CPU 只有一核,模拟出来多条线程。可以使用CPU快速交替,来模拟多线程。
并行:CPU多核,多个线程可以同时执行。 可以使用线程池。
获取CPU的核数:
// 获取CPU的核数
System.out.println(Runtime.getRuntime().availableProcessors());
wait / sleep:
- 1、来自不同的类 wait =>
Object
,sleep =>Thread
// 一般情况企业中使用休眠
import java.util.concurrent.TimeUnit;
TimeUnit.DAYS.sleep(1); //休眠1天
TimeUnit.SECONDS.sleep(1); //休眠1s
- 2、关于锁的释放 wait 会释放锁,sleep不会释放锁
- 3、使用的范围是不同的 wait 必须在同步代码块中,sleep 可以在任何地方睡
- 4、是否需要捕获异常 sleep 必须要捕获异常,wait 也是需要捕获异常,notify 和 notifyAll 不需要捕获异常
锁
传统的 synchronized
public class test {
public static void main(String[] args) {
//并发:多线程操作同一个资源类,将资源类丢入线程中
Ticket ticket = new Ticket();
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;
//卖票的方式
public synchronized void sale() {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票剩余" + number + "张票");
}
}
}
Lock 锁
// ReentrantLock源码
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync(); //非公平锁:十分不公平,可以插队;(默认为非公平锁)
}
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync(); //公平锁:十分公平,必须先来后到
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class test {
public static void main(String[] args) {
Ticket2 ticket = new Ticket2();
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();
}
}
//lock三部曲
//1、 Lock lock=new ReentrantLock();
//2、 lock.lock() 加锁
//3、 finally=> 解锁:lock.unlock();
class Ticket2 {
private int number = 30;
// 创建锁
Lock lock = new ReentrantLock();
//卖票的方式
public void sale() {
lock.lock(); // 开启锁
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票剩余" + number + "张票");
}
} finally {
lock.unlock(); // 关闭锁
}
}
}
Synchronized 与 Lock 的区别
- Synchronized 内置的 Java关键字,Lock是一个 Java 类。
- Synchronized 无法判断获取锁的状态,Lock可以判断。
- Synchronized 会自动释放锁,Lock 必须要手动加锁和手动释放锁,可能会遇到死锁。
- Synchronized 线程1(获得锁->阻塞)、线程2(等待);Lock 就不一定会一直等待下去,Lock 会有一个trylock 去尝试获取锁,不会造成长久的等待。
- Synchronized 是可重入锁,不可以中断的,非公平的;Lock是可重入的,可以判断锁,可以自己设置公平锁和非公平锁。
- Synchronized 适合锁少量的代码同步问题,Lock适合锁大量的同步代码。
生产者和消费者问题
Synchronized 版
- Synchronized、wait、notify
/**
* 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒
* 线程交替执行 A B 操作同一个变量 num = 0
* A num+1
* B num-1
*/
//顺序:判断待->业务->通知
public class test {
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 number = 0;
//+1
public synchronized void increment() throws InterruptedException {
if (number != 0) {
//等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我-1完毕了
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
if (number == 0) {
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我-1完毕了
this.notifyAll();
}
}
/*
A=>1
B=>0
A=>1
B=>0
...
*/
俩个加俩个减 存在问题(虚假唤醒):
如果有四个线程,会出现虚假唤醒。
if 改为 while 即可,防止虚假唤醒。
结论:
就是用 if 判断的话,唤醒后线程会从 wait 之后的代码开始运行,但是不会重新判断if条件,直接继续运行 if 代码块之后的代码,而如果使用 while 的话,也会从 wait 之后的代码运行,但是唤醒后会重新判断循环条件,如果不成立再执行 while 代码块之后的代码块,成立的话继续 wait。这也就是为什么用 while 而不用if的原因了,因为线程被唤醒后,执行开始的地方是 wait 之后。
public class test {
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();
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 Data {
private int number = 0;
//+1
public synchronized void increment() throws InterruptedException {
while (number != 0) {
//等待
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我-1完毕了
this.notifyAll();
}
//-1
public synchronized void decrement() throws InterruptedException {
while (number == 0) {
//等待
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "=>" + number);
// 通知其他线程,我-1完毕了
this.notifyAll();
}
}
Lock版
- Lock、await(Condition)、signal(Condition)
public class test {
public static void main(String[] args) {
Data2 data = new Data2();
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 Data2 {
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();
}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();
}finally {
lock.unlock();
}
}
}
Condition 的优势:精准通知和唤醒线程
要指定通知的下一个进行顺序,可以使用 Condition 来指定通知进程。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Description:
* A 执行完 调用B
* B 执行完 调用C
* C 执行完 调用A
**/
public class test {
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 {
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 3C
public void printA() {
lock.lock();
try {
// 业务代码 判断 -> 执行 -> 通知
while (num != 1) {
condition1.await();
}
System.out.println(Thread.currentThread().getName() + "==> AAAA" );
// 唤醒,唤醒指定的人B
num = 2;
condition2.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
// 业务代码 判断 -> 执行 -> 通知
while (num != 2) {
condition2.await();
}
System.out.println(Thread.currentThread().getName() + "==> BBBB" );
num = 3;
condition3.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
// 业务代码 判断 -> 执行 -> 通知
while (num != 3) {
condition3.await();
}
System.out.println(Thread.currentThread().getName() + "==> CCCC" );
num = 1;
condition1.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
/*
A==> AAAA
B==> BBBB
C==> CCCC
A==> AAAA
B==> BBBB
C==> CCCC
...
*/
8 锁现象
如何判断锁的是谁?锁会锁住:对象、Class
问题1:两个同步方法,先执行发短信还是打电话?
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(() -> {
phone.sendMs();
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone.call();
}).start();
}
}
class Phone {
public synchronized void sendMs() {
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
}
//发短信
//打电话
问题2:问题1基础上让发短信延迟 4s
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(() -> {
try {
phone.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone.call();
}).start();
}
}
class Phone {
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
}
//发短信
//打电话
问题一问题二说明并不是顺序执行,而是 synchronized 锁住的对象是方法的调用,对于两个方法用的是同一个锁,谁先拿到谁先执行,另外一个等待。
问题三:换成一个普通方法结果?
hello 是一个普通方法,不受 synchronized 锁的影响,不用等待锁的释放。
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(() -> {
try {
phone.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone.hello();
}).start();
}
}
class Phone {
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
//hello
//发短信
问题四:如果使用的是两个对象,一个调用发短信,一个调用打电话,那么整个顺序是怎么样的呢?
两个对象两把锁,不会出现等待的情况,发短信睡了4s,所以先执行打电话
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(() -> {
try {
phone1.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone2.call();
}).start();
}
}
class Phone {
public synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
//打电话
//发短信
问题五、六:如果我们把 synchronized 的方法加上 static 变成静态方法,那么顺序又是怎么样的呢?
static 静态方法来说,对于整个类 Class 来说只有一份,对于不同的对象使用的是同一份方法,相当于这个方法是属于类的,如果静态 static 方法使用 synchronized 锁定,那么这个 synchronized 锁会锁住整个对象,不管多少个对象,对于静态的锁都只有一把锁,谁先拿到这个锁就先执行,其他的进程都需要等待。
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
Phone.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
Phone.call();
}).start();
}
}
class Phone {
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public static synchronized void call() {
System.out.println("打电话");
}
}
//发短信
//打电话
问题七:如果使用一个静态同步方法、一个同步方法、一个对象调用顺序是什么?
因为一个锁的是Class类的模板,一个锁的是对象的调用者。所以不存在等待,直接运行
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
// Phone phone2 = new Phone();
new Thread(() -> {
try {
Phone.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone1.call();
}).start();
}
}
class Phone {
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
//打电话
//发短信
问题八:如果我们使用一个静态同步方法、一个同步方法、两个对象调用顺序是什么?
两把锁锁的不是同一个东西
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(() -> {
try {
Phone.sendMs();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
phone2.call();
}).start();
}
}
class Phone {
public static synchronized void sendMs() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println("发短信");
}
public synchronized void call() {
System.out.println("打电话");
}
public void hello() {
System.out.println("hello");
}
}
//打电话
//发短信
集合不安全
List 不安全
java.util.ConcurrentModificationException
并发修改异常,ArrayList 在并发情况下是不安全的
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
//java.util.ConcurrentModificationException 并发修改异常!
public class test {
public static void main(String[] args) {
List<Object> arrayList = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
new Thread(() -> {
arrayList.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(arrayList);
}, String.valueOf(i)).start();
}
}
}
原因:
// ArrayList源码的add
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
// Vector源码的add
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
// CopyOnWriteArrayList源码的add
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
解决方案
public class test {
public static void main(String[] args) {
/**
* 解决方案
* 1. List<String> list = new Vector<>();
* 2. List<String> list = Collections.synchronizedList(new ArrayList<>());
* 3. List<String> list = new CopyOnWriteArrayList<>();
*/
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();
}
}
}
CopyOnWriteArrayList:写入时复制! COW 计算机程序设计领域的一种优化策略
核心思想:
如果有多个调用者(Callers)同时要求相同的资源(如内存或者是磁盘上的数据存储),他们会共同获取相同的指针指向相同的资源,直到某个调用者视图修改资源内容时,系统才会真正复制一份专用副本(private copy)给该调用者,而其他调用者所见到的最初的资源仍然保持不变。这过程对其他的调用者都是透明的(transparently)。此做法主要的优点是如果调用者没有修改资源,就不会有副本(private copy)被创建,因此多个调用者只是读取操作时可以共享同一份资源。
读的时候不需要加锁,如果读的时候有多个线程正在向 CopyOnWriteArrayList 添加数据,读还是会读到旧的数据,因为写的时候不会锁住旧的 CopyOnWriteArrayList。
多个线程调用的时候 list,读取的时候,是固定的,写入(存在覆盖操作);在写入的时候避免覆盖,造成数据错乱的问题。
Set 不安全
java.util.ConcurrentModificationException
并发修改异常
//java.util.ConcurrentModificationException 并发修改异常!
public class test {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
for (int i = 1; i <= 50; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
}, String.valueOf(i)).start();
}
}
}
解决方法
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
public class test {
public static void main(String[] args) {
/**
* 1. Set<String> set = Collections.synchronizedSet(new HashSet<>());
* 2. Set<String> set = new CopyOnWriteArraySet<>();
*/
Set<String> set = new CopyOnWriteArraySet<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
set.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(set);
},String.valueOf(i)).start();
}
}
}
HashSet 底层是什么?
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
Map 不安全
HashMap 基础类也存在并发修改异常。java.util.ConcurrentModificationException
并发修改异常。
HashMap:默认加载因子是0.75,默认的初始容量是16
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public class MapTest {
public static void main(String[] args) {
/**
* 解决方案
* 1. Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
* Map<String, String> map = new ConcurrentHashMap<>();
*/
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 1; i < 100; i++) {
new Thread(()->{
map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
System.out.println(map);
},String.valueOf(i)).start();
}
}
}
Callable
Callable 接口类似于 Runnable ,因为它们都是为其实例可能由另一个线程执行的类设计的。 然而, Runnable 不返回结果,也不能抛出被检查的异常。
- 1、可以有返回值
- 2、可以抛出异常
- 3、方法不同,run() / call()
Runnable:
java.lang
Interface Runnable
All Known Subinterfaces:
RunnableFuture <V>, RunnableScheduledFuture <V>
所有已知实现类:
AsyncBoxView.ChildState , ForkJoinWorkerThread , FutureTask , RenderableImageProducer , SwingWorker , Thread , TimerTask
FutureTask:
构造方法:
FutureTask(Callable<V> callable)
创建一个 FutureTask ,它将在运行时执行给定的 Callable 。
FutureTask(Runnable runnable, V result)
创建一个 FutureTask ,将在运行时执行给定的 Runnable ,并安排 get将在成功完成后返回给定的结果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//new Thread(new Runnable()).start();
//new Thread(new FutureTask<V>()).start();
//new Thread(new FutureTask<V>( Callable )).start();
//new Thread().start();// 怎么启动Callable
MyThread thread = new MyThread();
FutureTask futureTask = new FutureTask(thread);//适配类
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();// 结果会被缓存,效率高,结果只打印一次
//获取Callable的返回结果
String o = (String) futureTask.get();//这个get方法可能会产生阻塞!把他放到最后或者使用异步通信来处理!
System.out.println(o);
}
}
class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("jjjj");
// 耗时的操作
return "hello";
}
}
常用的高并发辅助类
CountDownLatch 减法计数器
//例子:等人都离开了再关门
import java.util.concurrent.CountDownLatch;
public class test {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" 出去");
countDownLatch.countDown(); //countDown 减一操作
},String.valueOf(i)).start();
}
countDownLatch.await(); //await 等待计数器归零
System.out.println("关门");
}
}
CyclickBarrier 加法计数器
//集齐7颗龙珠召唤神龙
public class test {
public static void main(String[] args) {
// 召唤龙珠的线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("召唤神龙!");
});
for (int i = 1; i <= 7; i++) {
// lambda不能操作到 i
final int temp = 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();
}
}
}
CyclicBarrier 与 CountDownLatch 区别
- CountDownLatch 是一次性的,CyclicBarrier 是可循环利用的。
- CountDownLatch 参与的线程的职责是不一样的,有的在倒计时,有的在等待倒计时结束。CyclicBarrier 参与的线程职责是一样的。
Semaphore 信号量
semaphore.acquire();
获得,假设如果已经满了,等待,等待被释放为止。
semaphore.release();
释放,会将当前的信号量释放 + 1,然后唤醒等待的线程。
作用:
多个共享资源互斥的使用。并发限流,控制最大的线程数。
// 抢车位
public class test {
public static void main(String[] args) {
// 线程数量:停车位3 用来限流
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
//acquire() 得到
//release() 释放
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "抢到车位!");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "离开车位!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
读写锁(ReadWriteLock)
java.util.concurrent.locks
下 Interface ReadWriteLock
不加锁的情况,多线程的读写会造成数据不可靠的问题:
import java.util.*;
public class test {
public static void main(String[] args) {
MyCache myCache = new MyCache();
int num = 6;
for (int i = 1; i <= num; i++) {
int finalI = i;
new Thread(() -> {
myCache.write(String.valueOf(finalI), String.valueOf(finalI));
},String.valueOf(i)).start();
}
for (int i = 1; i <= num; i++) {
int finalI = i;
new Thread(() -> {
myCache.read(String.valueOf(finalI));
},String.valueOf(i)).start();
}
}
}
/**
* 方法未加锁,导致写的时候被插队
*/
class MyCache {
private volatile Map<String, String> map = new HashMap<>();
public void write(String key, String value) {
System.out.println(Thread.currentThread().getName() + "线程开始写入");
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "线程写入ok");
}
public void read(String key) {
System.out.println(Thread.currentThread().getName() + "线程开始读取");
map.get(key);
System.out.println(Thread.currentThread().getName() + "线程写读取ok");
}
}
/*
1线程开始写入
2线程开始写入
2线程写入ok
3线程开始写入
3线程写入ok
1线程写入ok
...
*/
可以采用 synchronized 这种重量锁和轻量锁 lock去保证数据的可靠。但是这次采用更细粒度的锁:ReadWriteLock 读写锁来保证。
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class test {
public static void main(String[] args) {
MyCache2 myCache = new MyCache2();
int num = 6;
for (int i = 1; i <= num; i++) {
int finalI = i;
new Thread(() -> {
myCache.write(String.valueOf(finalI), String.valueOf(finalI));
},String.valueOf(i)).start();
}
for (int i = 1; i <= num; i++) {
int finalI = i;
new Thread(() -> {
myCache.read(String.valueOf(finalI));
},String.valueOf(i)).start();
}
}
}
class MyCache2 {
private volatile Map<String, String> map = new HashMap<>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void write(String key, String value) {
lock.writeLock().lock(); // 写锁
try {
System.out.println(Thread.currentThread().getName() + "线程开始写入");
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "线程写入ok");
}finally {
lock.writeLock().unlock(); // 释放写锁
}
}
public void read(String key) {
lock.readLock().lock(); // 读锁
try {
System.out.println(Thread.currentThread().getName() + "线程开始读取");
map.get(key);
System.out.println(Thread.currentThread().getName() + "线程写读取ok");
}finally {
lock.readLock().unlock(); // 释放读锁
}
}
}
阻塞队列
队列:FIFO
阻塞队列写入:如果队列满了,就必须阻塞等待;阻塞队列取:如果队列是空的,必须阻塞等待生产。
java.util.concurrent
中 Interface BlockingQueue<E>
BlockQueue
是 Collection 的一个子类。什么情况下会使用阻塞队列:多线程并发处理、线程池。
BlockingQueue 有四组 API
方式 | 抛出异常 | 不会抛出异常,有返回值 | 阻塞,等待 | 超时等待 |
---|---|---|---|---|
添加 | add | offer | put | offer (timenum.timeUnit) |
移出 | remove | poll | take | poll (timenum,timeUnit) |
判断队首元素 | element | peek | - | - |
// 抛出异常
import java.util.concurrent.ArrayBlockingQueue;
public class test {
public static void main(String[] args) {
// 队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.element());//查看队首元素
System.out.println("---------------------");
//IllegalStateException: Queue full
//System.out.println(blockingQueue.add("d"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//java.util.NoSuchElementException 抛出异常!
//System.out.println(blockingQueue.remove());
}
}
// 有返回值,不抛出异常
import java.util.concurrent.ArrayBlockingQueue;
public class test {
public static void main(String[] args) {
// 队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println("---------------------");
System.out.println(blockingQueue.peek());//查看队首元素
System.out.println(blockingQueue.offer("d"));// false 不抛出异常!
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll()); // null 不抛出异常!
}
}
// 等待,阻塞(一直阻塞)
import java.util.concurrent.ArrayBlockingQueue;
public class test {
public static void main(String[] args) throws InterruptedException {
// 队列的大小
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
// 一直阻塞
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
// blockingQueue.put("d"); // 队列没有位置了,会一直阻塞
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take()); // 没有这个元素,一直阻塞
}
}
// 等待,阻塞(等待超时)
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class test {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.offer("a");
blockingQueue.offer("b");
blockingQueue.offer("c");
System.out.println("开始等待");
blockingQueue.offer("d",2, TimeUnit.SECONDS); //超时时间2s 等待如果超过2s就结束等待
System.out.println("结束等待");
System.out.println("===========取值==================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println("开始等待");
blockingQueue.poll(2,TimeUnit.SECONDS); //超过两秒 我们就不要等待了
System.out.println("结束等待");
}
}
同步队列
- 同步队列没有容量,也可以视为容量为1的队列。
- 进去一个元素,必须等待取出来之后,才能再往里面放入一个元素。
- put 方法 和 take方法。
- Synchronized 和 其他的 BlockingQueue 不一样 它不存储元素。
- put 了一个元素,就必须从里面先 take 出来,否则不能再put进去值。
- 并且 SynchronousQueue 的 take 是使用了 lock 锁保证线程安全的。
import java.util.concurrent.BlockingQueue;
public class test {
public static void main(String[] args){
BlockingQueue<String> synchronousQueue = new java.util.concurrent.SynchronousQueue<>();
// 往同步队列中添加元素
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "put 01");
synchronousQueue.put("1");
System.out.println(Thread.currentThread().getName() + "put 02");
synchronousQueue.put("2");
System.out.println(Thread.currentThread().getName() + "put 03");
synchronousQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
// 取出元素
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
//不能满足结果是先put后take,不能保证原子操作
线程池
线程池:三大方法、7大参数、4种拒绝策略。
程序的运行,本质是占用系统的资源,我们需要去优化资源的使用。线程池、JDBC的连接池、内存池、对象池 等等…资源的创建、销毁十分消耗资源。
池化技术:事先准备好一些资源,如果有人要用,就来拿,用完之后还,以此来提高效率。
线程池的好处:
-
1、降低资源的消耗
-
2、提高响应的速度
-
3、方便管理
线程复用、可以控制最大并发数、管理线程
线程池三种方法
-
ExecutorService threadPool = Executors.newSingleThreadExecutor();
//单个线程 -
ExecutorService threadPool2 = Executors.newFixedThreadPool(5);
//创建一个固定的线程池的大小 -
ExecutorService threadPool3 = Executors.newCachedThreadPool();
//可伸缩的
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors 工具类, 3大方法
public class test {
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++) {
//new Thread().start();
// 使用了线程池之后,使用线程池来创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 线程池用完,程序结束,关闭线程池
threadPool.shutdown();
}
}
}
线程池七种参数
三者本质上都是调用 ThreadPoolExecutor
// newSingleThreadExecutor源码
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
// newFixedThreadPool源码
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
// newCachedThreadPool源码
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,// 阻塞队列
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;
}
理解七大参数:
阻塞队列满了的时候,才会触发最大连接数。
import java.util.concurrent.*;
public class test {
public static void main(String[] args) {
// 自定义线程池!工作 ThreadPoolExecutor
ExecutorService threadPool = new ThreadPoolExecutor(2,
5,
3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy() //银行人满了,还有人进来,不处理这个人,抛出异常
);
try {
// 最大承载:Deque + max
// 超过 抛出异常: RejectedExecutionException
for (int i = 1; i <= 4; 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()
//队列满了,尝试去和最早的竞争,也不会抛出异常
设置线程池的大小(调优)
CPU密集型:电脑的核数是几核就选择几;选择 maximunPoolSize 的大小。
I/O密集型:例如在程序中有15个大型任务,IO十分占用资源;I/O密集型就是判断程序中十分耗I/O的线程数量,大约是最大I/O数的一倍到两倍之间。
// 获取cpu 的核数
int max = Runtime.getRuntime().availableProcessors();
ExecutorService service =new ThreadPoolExecutor(
2,
max,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
四大函数式接口
函数式接口:只有一个方法的接口 @FunctionalInterface
//例如 Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
- Function<T, R>
R apply(T t)
- Predicate<T>
boolean test(T t)
- Supplier<T>
T get()
- Consumer<T>
void accept(T t)
Function<T, R> 函数型接口 R apply(T t)
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
...
}
import java.util.function.Function;
/**
* Function 函数型接口, 有一个输入参数,有一个输出,
* 只要是函数型接口,就可以用 lambda表达式简化
*/
public class test {
public static void main(String[] args) {
//工具类:输出输入的值
Function function = new Function<Integer, String>() {
@Override
public String apply(Integer str) {
return str.toString();
}
};
//只要是函数型接口,就可以用 lambda表达式简化
Function function1 = (str) -> {
return str;
};
System.out.println(function1.apply(123));
}
}
Predicate<T> 断定型接口 test(T t)
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
...
}
import java.util.function.Predicate;
/**
* 断定型接口:有一个输入参数,返回值只能是布尔值
*/
public class test {
public static void main(String[] args) {
//判断字符串是否为空
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String str) {
return str.isEmpty();
}
};
//只要是函数型接口,就可以用 lambda表达式简化
Predicate<String> predicate2 = (str) -> {
return str.isEmpty();
};
System.out.println(predicate.test("asddd"));
}
}
Supplier<T> 供给型接口 T get()
@FunctionalInterface
public interface Supplier<T> {
T get();
}
import java.util.function.Supplier;
/**
* Supplier 供给型接口没有参数,只有返回值
*/
public class test {
public static void main(String[] args) {
Supplier supplier = new Supplier<Integer>() {
@Override
public Integer get() {
return 1024;
}
};
//只要是函数型接口,就可以用 lambda表达式简化
Supplier supplier2 = () -> {
return 1024;
};
System.out.println(supplier2.get());
}
}
Consumer<T> 消费型接口 void accept(T t)
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
...
}
import java.util.function.Consumer;
/**
* Consumer 消费型接口: 只有输入,没有返回值
*/
public class test {
public static void main(String[] args) {
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
//只要是函数型接口,就可以用 lambda表达式简化
Consumer<String> consumer1 = (str)->{
System.out.println(str);
};
consumer.accept("qwre");
}
}
Stream 流式计算
import java.util.Arrays;
import java.util.List;
/**
* 题目要求:一分钟内完成此题,只能用一行代码实现!
* 现在有5个用户!筛选:
* 1、ID 必须是偶数
* 2、年龄必须大于23岁
* 3、用户名转为大写字母
* 4、用户名字母倒着排序
* 5、只输出一个用户!
*/
public class test {
public static void main(String[] args) {
User u1 = new User(1, "a", 21);
User u2 = new User(2, "b", 22);
User u3 = new User(3, "c", 23);
User u4 = new User(4, "d", 24);
User u5 = new User(6, "e", 25);
// 集合是存储
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
// 计算交给Stream流
list.stream()
.filter(u -> {
return u.getId() % 2 == 0;
})
.filter(u -> {
return u.getAge() > 23;
})
.map(u -> {
return u.getName().toUpperCase();
})
.sorted((o1, o2) -> {
return o2.compareTo(o1);
})
.limit(1)
.forEach(System.out::println);
}
}
class User {
private int id;
private String name;
private int age;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
ForkJoin 分治并行执行
并行执行任务,提高效率:
ForkJoin 特点: 工作窃取;实现原理是:双端队列。
- 通过 ForkJoinPool 来执行
- 计算任务
execute(ForkJoinTask<?> task)
void execute(ForkJoinTask<?> task)
为异步执行给定任务的排列。
- 计算类要去继承 ForkJoinTask
import java.util.concurrent.RecursiveTask;
public class ForkJoinDemo extends RecursiveTask<Long> {
private long star;
private long end;
// 临界值
private long temp = 1000000L;
public ForkJoinDemo(long star, long end) { this.star = star; this.end = end; }
// 计算方法
@Override
protected Long compute() {
if ((end - star) < temp) {
Long sum = 0L;
for (Long i = star; i < end; i++) {
sum += i;
}
return sum;
}else {
// 使用ForkJoin 分而治之 计算
//1 . 计算平均值
long middle = (star + end) / 2;
ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(star, middle);
// 拆分任务,把线程压入线程队列
forkJoinDemo1.fork();
ForkJoinDemo forkJoinDemo2 = new ForkJoinDemo(middle, end);
forkJoinDemo2.fork();
long taskSum = forkJoinDemo1.join() + forkJoinDemo2.join();
return taskSum;
}
}
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
public class test {
private static final long SUM = 20_0000_0000;
public static void main(String[] args) throws ExecutionException, InterruptedException {
test1();
test2();
test3();
}
// 使用普通方法
public static void test1() {
long star = System.currentTimeMillis();
long sum = 0L;
for (long i = 1; i < SUM ; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println(sum);
System.out.println("时间:" + (end - star));
System.out.println("----------------------");
}
// 使用ForkJoin 方法
public static void test2() throws ExecutionException, InterruptedException {
long star = System.currentTimeMillis();
//通过ForkJoinPool来执行
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinDemo(0L, SUM);
ForkJoinTask<Long> submit = forkJoinPool.submit(task);
Long sum = submit.get();
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("时间:" + (end - star));
System.out.println("-----------");
}
//使用 Stream 流计算
public static void test3() {
long star = System.currentTimeMillis();
// .parallel().reduce(0, Long::sum)使用一个并行流去计算整个计算,提高效率
long sum = LongStream.range(0L, 20_0000_0000L).parallel().reduce(0, Long::sum);
System.out.println(sum);
long end = System.currentTimeMillis();
System.out.println("时间:" + (end - star));
System.out.println("-----------");
}
}