1. CountDownLatch
CountDownLatch:当所有的子线程完成任务,主线程才能结束
- 使用CountDownLatch:当一个或者多个线程调用await方法时,线程会阻塞,其他线程调用countDown方法会将计数器-1(调用countDown方法的线程不会阻塞);
- 当计数器变为0时,此时被await方法阻塞的线程才会被唤醒,继续执行
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch count = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 结束...");
count.countDown(); // 每次一个子线程完成 计数-1
}, String.valueOf(i)).start();
}
try {
count.await(); // 在所有的子线程执行完成之前 主线程必须等待
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 子线程全部执行完...总程序执行结束...");
}
}
2. CyclicBarrier
CyclicBarrier(int parties, Runnable barrierAction):在给定数量的参与者(线程)全部处于等待状态时启动,并在启动barrier时执行给定的屏障操作。该操作由最后一个进入barrier的线程执行
- int parties 参与者的数量
- Runnable barrierAction 线程全部就绪后执行的方法
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(7, () -> {
System.out.println("线程全部就绪...开始执行...");
});
for(int i=1; i<=7; i++){
int finalI = i;
new Thread( () -> {
System.out.println(Thread.currentThread().getName() + "第 " + finalI + "线程就绪");
try{
barrier.await();
}catch (Exception e){
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
3. Semaphore
使用信号量Semaphore的目的:用于多个共享资源的互斥使用;并发线程数的控制(可替换Synchronized)
在信号量semaphore上定义两种操作:
-
acquire获取:当一个线程调用acquire操作时,要么通过成功获取信号量(信号量-1);要么一直等待下去,直到有线程释放信号量或者超时
-
release释放:实际上信号量的值+1,然后唤醒等待的线程
注意:当创建信号量传递的资源数只有1个,相当于使用了加锁synchronized
public class SemaphoreDemo {
public static void main(String[] args) {
// 模拟资源类有三个
Semaphore semaphore = new Semaphore(3);
// 6个线程去抢占资源,每当一个线抢占到资源占用4秒
for(int i=1; i<=6; i++){
new Thread(() -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 抢占资源");
try {
TimeUnit.SECONDS.sleep(4);
System.out.println(Thread.currentThread().getName() + " 释放资源");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release(); // 释放资源后需要将资源数+1
}
}, String.valueOf(i)).start();
}
}
}
4. 阻塞队列BlockingQueue
阻塞:某些情况会挂起线程,一旦条件满足,又会被唤醒
-
为什么需要阻塞队列:不需要关心什么时候要阻塞线程,什么时候需要唤醒,交给BlockingQueue来完成
-
阻塞队列是一个队列,Thread1在队列头,Thread2在队列尾
-
线程1往阻塞队列中添加,线程2移除从空的队列中获取元素的线程被阻塞,直到其他线程在空的队列中增加元素。从满的队列中增加元素的线程被阻塞,直到其他线程在队列中移除一个或者多个
-
BlockingQueue继承Queue,BlockingQueue的实现类有:
- ArrayBlockingQueue 数组结构的有界阻塞队列
- LinkedBlockingQueue 链表结构的有界阻塞队列
- SynchronousQueue 不存储元素的阻塞队列 也就是单个元素的队列
其中的API有:
-
当队列满时 再添加元素add报错:IllegalStateException: Queue full
-
当队列空时 再移除元素remove报错:IllegalStateException: NoSuchElementException
-
使用offer和poll不抛异常,只是返回true/false/null
-
而使用put方法,队列满时会一直进行等待 直至有空位置; 使用take方法,队列空时会一直进行等待 直至有元素可以取
-
offer(E e, long timeout, TimeUnit unit) 设置超时时间 不会一直等待下去
-
poll(long timeout, TimeUnit unit) 设置超时时间 不会一直等待下去 时间到没有值则返回null
方法类型 | 抛出异常 | 特殊值 | 阻塞 | 超时 |
---|---|---|---|---|
插入 | add(E e) | offer(e) | put(e) | offer(e, time, unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
检查 | element() | peek() | 不可用 | 不可用 |
SynchronousQueue:不存储元素的阻塞队列,即单个元素的队列;每一个put操作,都必须要等待一个take操作,否则不能继续添加元素,反之亦然
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class SynchronousQueueDemo {
public static void main(String[] args) {
// 默认是非公平锁
BlockingQueue<String> queue = new SynchronousQueue<>();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName()+ "\t put 111");
queue.put("111");
System.out.println(Thread.currentThread().getName()+ "\t put 222");
queue.put("222");
System.out.println(Thread.currentThread().getName()+ "\t put 333");
queue.put("333");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "A").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + queue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + queue.take());
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "\t" + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "B").start();
}
}
使用BlockingQueue实现生产者-消费者问题,不需要加锁Lock或者synchronized:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class Resources{
private volatile boolean flag = true; // 默认开启 生产+消费
private AtomicInteger atomicInteger = new AtomicInteger();
BlockingQueue<String> queue = null;
// 通过构造方法来创建BlockingQueue
public Resources(BlockingQueue<String> queue) {
this.queue = queue;
System.out.println("当前阻塞队列类型为:" + queue.getClass().getName());
}
public void Product() throws InterruptedException {
String data = null;
boolean returnValue;
while(flag){
data = atomicInteger.incrementAndGet() + "";
returnValue = queue.offer(data, 2, TimeUnit.SECONDS);
if(returnValue){
System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "成功");
}else{
System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "失败");
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println(Thread.currentThread().getName() + "\t 生产结束!");
}
public void Consumer() throws InterruptedException {
String res = null;
while(flag){
res = queue.poll(2, TimeUnit.SECONDS);
if(res == null || res.equalsIgnoreCase("")){
flag = false;
System.out.println(Thread.currentThread().getName()+ "\t 2s钟没等到值 出队暂停");
return;
}
System.out.println(Thread.currentThread().getName() + "\t 出队成功" + res);
}
}
public void stop(){
this.flag = false;
}
}
public class ProductConsumer_BlockQueueDemo {
public static void main(String[] args) {
Resources resources = new Resources(new ArrayBlockingQueue<>(10));
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t 生产线程启动");
try {
resources.Product();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t 消费线程启动");
try {
resources.Consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main线程停止... 生产消费结束");
resources.stop();
}
}
5. 死锁
死锁:两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉他们将无法推进下去
代码演示:
import java.util.concurrent.TimeUnit;
class holdLockThread implements Runnable{
private String lock1;
private String lock2;
public holdLockThread(String lock1, String lock2) {
this.lock1 = lock1;
this.lock2 = lock2;
}
@Override
public void run() {
synchronized (lock1){
System.out.println(Thread.currentThread().getName() + "\t 自己持有:" +lock1 + "\t 尝试获得:" + lock2);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2){
System.out.println(Thread.currentThread().getName() + "\t 自己持有:" +lock2 + "\t 尝试获得:" + lock1);
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
String lock1 = "AAA";
String lock2 = "BBB";
new Thread( new holdLockThread(lock1, lock2), "ThreadAAA").start();
new Thread( new holdLockThread(lock2, lock1), "ThreadBBB").start();
}
}
解决:
-
windows下查看java运行程序 类似ps的查看线程的命令 在IDEA的terminal中使用jps-l 定位哪一个线程
-
14812 com.hz.Interview.DeadLockDemo 线程id 出问题的线程
-
jstack 14812(线程id) 找到该线程的死锁查看