就是java util concurrent这个包下面的东西,学习JUC就是学习这个包下的各种东西
进程
a. 系统的一个运行单位
线程
a. 进程的一个运行单位
b. Java默认有两个线程,主线程和GC线程
c. Java本质上不能开启线程
并发(多人操作同一份资源)同一时间CPU的一个核心只能执行一个任务,那么多个任务就会共享时间片这就是并发
并行(多人一起走在路上)CPU核心数大于需要执行的任务数,同一时间点每个核心执行一个任务,就是并行
获取CPU核心数:
public static void main(String[] args) {
System.out.println(Runtime.getRuntime().availableProcessors());
}
并发编程的本质目标:充分利用CPU的资源
线程的状态:
public enum State {
// 新创建
NEW,
// 可运行
RUNNABLE,
// 阻塞
BLOCKED,
// 等待
WAITING,
// 超时等待
TIMED_WAITING,
// 终止
TERMINATED
}
Wait和Sleep的区别:
a. 来自不同的类,wait是Object的,sleep是Thread的
i. 不过企业开发中不太会用Thread.sleep,更多是TimeUnit.Seconds.sleep这种
b. wait会释放锁,sleep会抱着锁睡
c. wait必须在同步代码块中使用,sleep哪里都可以用
d. wait不用捕获异常,sleep则需要捕获异常
e. 案例:
package juc;
class Message {
private String message;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = true;
// 通知写线程可以写入新消息
notifyAll();
return message;
}
public synchronized void write(String message) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = false;
this.message = message;
// 通知读线程可以读取消息
notifyAll();
}
}
class ReaderThread extends Thread {
private final Message message;
public ReaderThread(Message message) {
this.message = message;
}
@Override
public void run() {
String msg = message.read();
System.out.println("读取消息: " + msg);
}
}
class WriterThread extends Thread {
private Message message;
public WriterThread(Message message) {
this.message = message;
}
@Override
public void run() {
message.write("Hello, World!");
System.out.println("写入消息: Hello, World!");
}
}
public class WaitNotifyExample {
public static void main(String[] args) {
Message message = new Message();
ReaderThread readerThread = new ReaderThread(message);
WriterThread writerThread = new WriterThread(message);
writerThread.start();
readerThread.start();
}
}
以经典的买票为案例
package juc;
/**
* 线程就是一个单独资源类,没有任何附属操作
* 它会包含以下部分:
* 1. 属性,方法
*/
public class SaleTicket {
public static void main(String[] args) {
// 并发:把资源类丢入线程
Ticket ticket = new Ticket();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "D").start();
}
}
class Ticket{
// 属性
private int ticketNumber = 10;
// 方法(此处为卖票的方式)
public void sale() {
if (ticketNumber > 0) {
System.out.printf("卖出了第%d张票,剩余%d张。由线程%s卖出 \r\n", ticketNumber--, ticketNumber, Thread.currentThread().getName());
}
}
}
public synchronized void sale() {
if (ticketNumber > 0) {
System.out.printf("卖出了第%d张票,剩余%d张。由线程%s卖出 \r\n", ticketNumber--, ticketNumber, Thread.currentThread().getName());
}
}
synchronized本质上是一个锁加队列,按照先到先得的顺序先后拿资源
package juc;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTicket2 {
public static void main(String[] args) {
// 并发:把资源类丢入线程
Ticket2 ticket = new Ticket2();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 20; ++i) {
ticket.sale();
}
}, "D").start();
}
}
class Ticket2 {
private int ticketNumber = 50;
// 初始化一个公平锁
private final Lock lock = new ReentrantLock(true);
public void sale() {
// 上锁
lock.lock();
// 业务代码放在try catch
try {
if (ticketNumber > 0) {
System.out.printf("卖出了第%d张票,剩余%d张。由线程%s卖出 \r\n", ticketNumber--, ticketNumber, Thread.currentThread().getName());
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
// 无论业务代码成功与否都强制解锁
lock.unlock();
}
}
}
总结lock使用三部曲:
那么重点来了,synchronized和lock的异同?
从生产者消费者模型看
package juc;
import java.util.concurrent.TimeUnit;
public class ProducerAndConsumer {
public static void main(String[] args) {
Products products = new Products();
Thread p1 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者1");
Thread p2 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者2");
Thread c1 = new Thread(() -> {
while (true) {
products.consume();
}
}, "消费者1");
Thread c2 = new Thread(() -> {
while (true) {
products.consume();
}
}, "消费者2");
p1.start();
p2.start();
c1.start();
c2.start();
}
}
class Products {
private int nums = 0;
public synchronized void produce() {
while (nums > 10) {
// 等待消费
try {
wait();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
nums++;
System.out.println(Thread.currentThread().getName() + "生产了一件产品,库存为:" + nums);
notifyAll();
}
public synchronized void consume() {
while (nums <= 0) {
// 等待生产
try {
wait();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
nums--;
System.out.println(Thread.currentThread().getName() + "消费了一件产品,库存为:" + nums);
notifyAll();
}
}
package juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerAndConsumer2 {
public static void main(String[] args) {
DataProduct products = new DataProduct();
Thread p1 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者1");
Thread p2 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者2");
Thread p3 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者3");
Thread p4 = new Thread(() -> {
while (true) {
products.produce();
}
}, "生产者4");
Thread c1 = new Thread(() -> {
while (true) {
products.consume();
}
}, "消费者1");
Thread c2 = new Thread(() -> {
while (true) {
products.consume();
}
}, "消费者2");
p1.start();
p2.start();
p3.start();
p4.start();
c1.start();
c2.start();
}
}
class DataProduct {
private int num = 0;
private final Lock produceLock = new ReentrantLock(true);
private final Lock consumeLock = new ReentrantLock(true);
public void produce(){
produceLock.lock();
try {
if (num <= 10) {
TimeUnit.SECONDS.sleep(2);
num++;
System.out.println(Thread.currentThread().getName() + "生产1产品,库存:" + num);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
produceLock.unlock();
}
}
public void consume() {
consumeLock.lock();
try {
if (num > 0) {
TimeUnit.MILLISECONDS.sleep(1500);
num--;
System.out.println(Thread.currentThread().getName() + "消费1产品,库存:" + num);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
consumeLock.unlock();
}
}
}
package juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerAndConsumer03 {
public static void main(String[] args) {
ProductsWarehouse warehouse = new ProductsWarehouse();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
warehouse.produce();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
warehouse.consume();
}
}, "B").start();
}
}
class ProductsWarehouse {
private final int MAXIMUM = 100;
// 仓库
private final int[] container = new int[MAXIMUM];
// 产品数量
private int counts = 0;
private int tptr, pptr;
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
public void produce() {
lock.lock();
try {
while (counts == MAXIMUM) {
notFull.await();
}
container[pptr] = 1;
if (++pptr == container.length) pptr = 0;
++counts;
System.out.printf("线程%s在%d仓库位置生产1份产品\r\n", Thread.currentThread().getName(), counts);
notEmpty.signal();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
public void consume() {
lock.lock();
try {
while (counts == 0) {
notEmpty.await();
}
container[tptr] = 0;
if (++tptr == MAXIMUM) tptr = 0;
--counts;
System.out.printf("线程%s在%d仓库位置消费1份产品\r\n", Thread.currentThread().getName(), counts);
notFull.signal();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
public void print() {
for (int i = 0; i <= counts; i++) {
System.out.println("仓库第" + i + "个位置的产品为" + container[i]);
}
}
}
本质上看就是一组对应关系
package juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用Lock和Condition精准地控制线程通信
*/
public class ProducerAndConsumer04 {
public static void main(String[] args) {
Data3 data3 = new Data3();
// 目标:A执行完通知B,B执行完通知C
new Thread(() -> {
while (true) data3.printA();
}, "A").start();
new Thread(() -> {{
while (true) data3.printB();
}}, "B").start();
new Thread(() -> {
while (true) data3.printC();
}, "C").start();
}
}
// 资源类
class Data3 {
private final Lock lock = new ReentrantLock();
private final Condition condition1 = lock.newCondition();
private final Condition condition2 = lock.newCondition();
private final Condition condition3 = lock.newCondition();
private int flag = 1;
public void printA() {
lock.lock();
try {
while (flag != 1) {
condition1.await();
}
System.out.println("A执行");
flag = 2;
condition2.signal();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
while (flag != 2) {
condition2.await();
}
System.out.println("B执行");
flag = 3;
condition3.signal();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
while (flag != 3) {
condition3.await();
}
System.out.println("C执行");
flag = 1;
condition1.signal();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
}
先打电话还是先发短信
package juc;
import java.util.concurrent.TimeUnit;
/**
* 八锁问题1,先打电话还是先发短信?
*/
public class LockQuestion1 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(phone::call, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(phone::sms, "B").start();
}
}
class Phone {
public void call() {
System.out.println("打电话");
}
public void sms() {
System.out.println("发短信");
}
}
a. 还是上面这个例子,如果call()方法中先睡眠4秒,是先打电话还是先发短信?
b. 一定都是call先执行。synchronized锁的对象是方法的调用者,所以在本案例中,phone实例的两个方法共享一把锁,谁先拿到谁先执行。这里call先拿到锁,所以先执行。也就是说,对于同一对象中的加锁方法,谁先出现在代码中谁先执行
有锁方法和无锁方法谁先谁后
package juc;
import java.util.concurrent.TimeUnit;
/**
* 普通方法和有锁方法谁先谁后?
*/
public class LockQustion3 {
public static void main(String[] args) {
Phone2 phone = new Phone2();
new Thread(phone::call, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(phone::hello, "B").start();
}
}
class Phone2 {
public synchronized void call() {
System.out.println("打电话");
}
public synchronized void sms() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("发短信");
}
public void hello() {
System.out.println("hello");
}
}
两个对象执行有锁方法,谁先谁后?
public static void main(String[] args) {
Phone2 phone = new Phone2();
Phone2 phone2 = new Phone2();
new Thread(phone::sms, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
new Thread(phone2::call, "B").start();
}
两个有锁的静态方法,谁先谁后?
a. 锁的是class对象,也就是类编译以后的类文件
b. 那么顺序其实和同一对象的锁没有差别
一个有锁的普通方法和一个有锁的静态方法,谁先谁后?
a. 静态方法在前
b. class对象必先于实例加锁
两个实例,一个调用静态同步方法一个调用普通同步方法
总结:
package juc;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class GoodsWarehouse {
private final Queue<Integer> container = new LinkedList<>();
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public void produce() {
lock.lock();
try {
int MAX_SIZE = 100;
while (container.size() == MAX_SIZE) {
notFull.await();
}
container.add(1);
System.out.println("[" + Thread.currentThread().getName() + "]" + "Produced one item. Current size: " + container.size());
notEmpty.signalAll();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
public void consume() {
lock.lock();
try {
while (container.isEmpty()) {
notEmpty.await();
}
container.poll();
System.out.println("[" + Thread.currentThread().getName() + "]" + "Consumed one item. Current size: " + container.size());
notFull.signalAll();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
private final GoodsWarehouse warehouse;
public Producer(GoodsWarehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(2000); // 生产需要 2 秒
warehouse.produce();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class Consumer implements Runnable {
private final GoodsWarehouse warehouse;
public Consumer(GoodsWarehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000); // 消费需要 1 秒
warehouse.consume();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class Main {
public static void main(String[] args) {
GoodsWarehouse warehouse = new GoodsWarehouse();
// 假设设置 3 个生产者线程和 6 个消费者线程,可根据实际情况调整比例
int numProducers = 6;
int numConsumers = 3;
Thread[] producers = new Thread[numProducers];
Thread[] consumers = new Thread[numConsumers];
for (int i = 0; i < numProducers; i++) {
producers[i] = new Thread(new Producer(warehouse), "生产线程" + i);
producers[i].start();
}
for (int i = 0; i < numConsumers; i++) {
consumers[i] = new Thread(new Consumer(warehouse), "消费线程" + i);
consumers[i].start();
}
}
}
public static void main(String[] args) {
List<String> arr = new ArrayList<>();
for (int i = 1; i <= 10; ++i) {
new Thread(() -> {
arr.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(arr);
}, "thread" + i).start();
}
}
在jdk1.8中必有异步修改异常,但是在jdk17中则未必有此异常,但这并不代表jdk17中arrayList是线程安全的,数据仍然有可能有问题,比如我们扩大数据量的时候就会报错
怎么解决呢?
public static void main(String[] args) {
List<String> arr = new CopyOnWriteArrayList<>();
for (int i = 1; i <= 100; ++i) {
new Thread(() -> {
arr.add(UUID.randomUUID().toString().substring(0, 5));
System.out.println(arr);
}, "thread" + i).start();
}
}
package juc;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 第一步 new Thread(Runnable).start()
// 第二步 new Thread(FutureTask).start()。其中futureTask是runnable的实现
// 第三步 new Thread可以使用callAble
FutureTask<String> futureTask = new FutureTask<>(new MineCall());
new Thread(futureTask).start();
System.out.println(
futureTask.get()
);
}
}
class MineCall implements Callable<String> {
@Override
public String call() throws Exception {
return "get res";
}
}
import java.util.concurrent.CountDownLatch;
public class TestCountdownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch downLatch = new CountDownLatch(6);
for (int i = 0; i < 6; ++i) {
new Thread(()-> {
System.out.println(Thread.currentThread().getName() + "go out");
downLatch.countDown();
}, i + "p ").start();
}
// 等所有线程都跑完
downLatch.await();
System.out.println("all run");
}
}
package juc.helpers;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
// 自定义可复用的 CountDownLatch 类
public class ReusableCountDownLatch {
// 内部类继承自 AbstractQueuedSynchronizer
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
// 尝试获取共享锁,只有当计数器为 0 时才能获取成功
@Override
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
// 尝试释放共享锁,每次调用将计数器减 1,当计数器为 0 时唤醒所有等待的线程
@Override
protected boolean tryReleaseShared(int releases) {
for (; ; ) {
int c = getState();
if (c == 0)
return false;
int nextc = c - 1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
// 重置计数器
void reset(int newCount) {
setState(newCount);
}
}
private final Sync sync;
// 构造函数,初始化计数器
public ReusableCountDownLatch(int count) {
if (count < 0)
throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
// 等待计数器归零
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
// 计数器减一
public void countDown() {
sync.releaseShared(1);
}
// 获取当前计数器的值
public int getCount() {
return sync.getCount();
}
// 重置计数器
public void reset(int newCount) {
if (newCount < 0)
throw new IllegalArgumentException("new count < 0");
sync.reset(newCount);
}
public static void main(String[] args) {
// 创建一个初始计数器为 3 的可复用 CountDownLatch
ReusableCountDownLatch latch = new ReusableCountDownLatch(3);
// 模拟三个线程完成任务
for (int i = 0; i < 3; i++) {
final int index = i;
new Thread(() -> {
System.out.println("Thread " + index + " is working.");
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + index + " has completed its task.");
latch.countDown();
}).start();
}
// 主线程等待所有任务完成
try {
latch.await();
System.out.println("All tasks are completed.");
// 重置计数器为 2
latch.reset(2);
// 模拟两个新线程完成任务
for (int i = 0; i < 2; i++) {
final int index = i;
new Thread(() -> {
System.out.println("New Thread " + index + " is working.");
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("New Thread " + index + " has completed its task.");
latch.countDown();
}).start();
}
// 主线程再次等待所有新任务完成
latch.await();
System.out.println("All new tasks are completed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package juc.helpers;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
// 运动员类,实现 Runnable 接口
class Athlete implements Runnable {
private final CyclicBarrier barrier;
private final String name;
public Athlete(CyclicBarrier barrier, String name) {
this.barrier = barrier;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(name + " 正在准备...");
// 模拟准备时间
Thread.sleep((long) (Math.random() * 5000));
System.out.println(name + " 已准备好,等待其他运动员...");
// 等待所有运动员都准备好
barrier.await();
System.out.println(name + " 开始起跑!");
} catch (InterruptedException | BrokenBarrierException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
public class CyclicBarrierExample {
public static void main(String[] args) {
// 定义运动员数量
int athleteCount = 5;
// 创建 CyclicBarrier,当所有运动员都准备好后,输出起跑信息
CyclicBarrier barrier = new CyclicBarrier(athleteCount, () -> System.out.println("所有运动员都已准备好,比赛开始!"));
// 创建并启动运动员线程
for (int i = 0; i < athleteCount; i++) {
new Thread(new Athlete(barrier, "运动员 " + (i + 1))).start();
}
try {
// 模拟比赛时间
Thread.sleep(10000);
System.out.println("第一轮比赛结束,准备进行下一轮比赛...");
// 再次启动新一轮比赛
for (int i = 0; i < athleteCount; i++) {
new Thread(new Athlete(barrier, "运动员 " + (i + 1))).start();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
package juc.helpers;
import java.util.concurrent.Semaphore;
// 车辆类,实现 Runnable 接口
class Car implements Runnable {
private static int carId = 1;
private final int id;
private final Semaphore semaphore;
public Car(Semaphore semaphore) {
this.id = carId++;
this.semaphore = semaphore;
}
@Override
public void run() {
try {
System.out.println("车辆 " + id + " 正在等待进入停车场...");
// 获取许可
semaphore.acquire();
System.out.println("车辆 " + id + " 已进入停车场。");
// 模拟停车时间
Thread.sleep((long) (Math.random() * 5000));
System.out.println("车辆 " + id + " 离开停车场。");
// 释放许可
semaphore.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
public class SemaphoreExample {
public static void main(String[] args) {
// 定义停车场的停车位数量
int parkingSpaces = 3;
// 创建 Semaphore,初始许可数量为停车位数量
Semaphore semaphore = new Semaphore(parkingSpaces);
// 模拟 5 辆车尝试进入停车场
for (int i = 0; i < 5; i++) {
new Thread(new Car(semaphore)).start();
}
}
}
针对大多数情况下读多写少的情况,把读写锁分离开
package juc.helpers;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
// 共享资源类
class SharedResource {
private int data;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
// 读操作
public int readData() {
// 获取读锁
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 开始读取数据...");
Thread.sleep(100); // 模拟读取耗时
System.out.println(Thread.currentThread().getName() + " 读取数据完成,数据值为: " + data);
return data;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
} finally {
// 释放读锁
lock.readLock().unlock();
}
}
// 写操作
public void writeData(int newData) {
// 获取写锁
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 开始写入数据...");
Thread.sleep(200); // 模拟写入耗时
data = newData;
System.out.println(Thread.currentThread().getName() + " 写入数据完成,新数据值为: " + data);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// 释放写锁
lock.writeLock().unlock();
}
}
}
public class ReadWriteLockExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
// 创建多个读线程
for (int i = 0; i < 3; i++) {
new Thread(resource::readData, "读线程 " + i).start();
}
// 创建写线程
new Thread(() -> resource.writeData(100), "写线程").start();
// 创建多个读线程
for (int i = 0; i < 3; i++) {
new Thread(resource::readData, "读线程 " + i).start();
}
}
}
BlockingQueue
是 Java 并发包 java.util.concurrent
中的一个接口,它继承自 Queue
接口。BlockingQueue
提供了线程安全的队列操作,并且在队列操作时支持阻塞行为。当队列满时,尝试向队列中插入元素的线程会被阻塞;当队列空时,尝试从队列中移除元素的线程会被阻塞。这种特性使得 BlockingQueue
非常适合用于生产者 - 消费者模式。
BlockingQueue
定义了四组不同的插入、移除和检查操作,每组操作在队列为空或满时的行为不同:
操作类型 | 抛出异常 | 返回特殊值 | 阻塞 | 超时 |
---|---|---|---|---|
插入 | add(e) |
offer(e) |
put(e) |
offer(e, time, unit) |
移除 | remove() |
poll() |
take() |
poll(time, unit) |
检查 | element() |
peek() |
无 | 无 |
null
或 false
。null
或 false
。ArrayBlockingQueue
:基于数组实现的有界阻塞队列,创建时需要指定队列的容量。LinkedBlockingQueue
:基于链表实现的阻塞队列,可以是有界的也可以是无界的(默认情况下是无界的)。PriorityBlockingQueue
:基于堆实现的无界阻塞队列,队列中的元素会按照自然顺序或指定的比较器进行排序。SynchronousQueue
:一种特殊的阻塞队列,它不存储元素,每个插入操作必须等待另一个线程的移除操作,反之亦然。import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Producer implements Runnable {
private final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("生产者生产: " + i);
queue.put(i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Consumer implements Runnable {
private final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Integer item = queue.take();
System.out.println("消费者消费: " + item);
Thread.sleep(200);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class BlockingQueueExample {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
}
}
BlockingDeque
是 BlockingQueue
的子接口,它继承自 Deque
接口,代表一个支持阻塞操作的双端队列。双端队列允许在队列的两端进行插入和移除操作,因此 BlockingDeque
提供了更多的操作灵活性。
BlockingDeque
除了继承 BlockingQueue
的方法外,还提供了在队列两端进行插入和移除的阻塞方法,例如:
putFirst(E e)
:将元素插入到队列的头部,如果队列已满则阻塞。putLast(E e)
:将元素插入到队列的尾部,如果队列已满则阻塞。takeFirst()
:从队列的头部移除并返回元素,如果队列为空则阻塞。takeLast()
:从队列的尾部移除并返回元素,如果队列为空则阻塞。LinkedBlockingDeque
是 BlockingDeque
的主要实现类,它基于链表实现,支持有界和无界的双端队列。
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
class DequeProducer implements Runnable {
private final BlockingDeque<Integer> deque;
public DequeProducer(BlockingDeque<Integer> deque) {
this.deque = deque;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("生产者在头部插入: " + i);
deque.putFirst(i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class DequeConsumer implements Runnable {
private final BlockingDeque<Integer> deque;
public DequeConsumer(BlockingDeque<Integer> deque) {
this.deque = deque;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Integer item = deque.takeLast();
System.out.println("消费者从尾部取出: " + item);
Thread.sleep(200);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class BlockingDequeExample {
public static void main(String[] args) {
BlockingDeque<Integer> deque = new LinkedBlockingDeque<>(3);
Thread producerThread = new Thread(new DequeProducer(deque));
Thread consumerThread = new Thread(new DequeConsumer(deque));
producerThread.start();
consumerThread.start();
}
}
BlockingQueue
是一个线程安全的队列,支持阻塞操作,适用于生产者 - 消费者模式。BlockingDeque
是 BlockingQueue
的子接口,支持双端的阻塞操作,提供了更多的操作灵活性。在选择使用时,根据具体的业务需求来决定是使用单端队列还是双端队列。为了实现在无界流分词统计词频,并使用双端阻塞队列以保证线程安全,我们可以采用生产者 - 消费者模式。生产者负责从输入流中读取数据并将其放入双端阻塞队列,消费者从队列中取出数据进行分词和词频统计。
以下是实现代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.regex.Pattern;
// 生产者类,负责从输入流读取数据并放入队列
class Producer implements Runnable {
private final BlockingDeque<String> queue;
public Producer(BlockingDeque<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String line;
// 持续读取输入,模拟无界流
while ((line = reader.readLine()) != null) {
// 将读取到的行放入队列
queue.put(line);
}
// 当输入结束时,放入一个特殊标记表示结束
queue.put("END_OF_INPUT");
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
// 消费者类,负责从队列中取出数据进行分词和词频统计
class Consumer implements Runnable {
private final BlockingDeque<String> queue;
private final Map<String, Integer> wordFrequency;
private static final Pattern WORD_PATTERN = Pattern.compile("\\W+");
public Consumer(BlockingDeque<String> queue, Map<String, Integer> wordFrequency) {
this.queue = queue;
this.wordFrequency = wordFrequency;
}
@Override
public void run() {
try {
String line;
while (true) {
// 从队列中取出数据
line = queue.take();
// 检查是否为结束标记
if ("END_OF_INPUT".equals(line)) {
break;
}
// 对读取到的行进行分词
String[] words = WORD_PATTERN.split(line.toLowerCase());
for (String word : words) {
if (!word.isEmpty()) {
// 更新词频
wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
public class WordFrequencyCounterWithQueue {
public static void main(String[] args) {
// 创建双端阻塞队列
BlockingDeque<String> queue = new LinkedBlockingDeque<>();
// 用于存储词频的 Map
Map<String, Integer> wordFrequency = new HashMap<>();
// 创建生产者和消费者线程
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue, wordFrequency));
// 启动线程
producerThread.start();
consumerThread.start();
try {
// 等待生产者线程完成
producerThread.join();
// 等待消费者线程完成
consumerThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
// 输出统计结果
for (Map.Entry<String, Integer> entry : wordFrequency.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
LinkedBlockingDeque
作为双端阻塞队列,它可以保证线程安全,并且支持阻塞操作。当队列满时,生产者线程会被阻塞;当队列空时,消费者线程会被阻塞。Producer
类):
"END_OF_INPUT"
表示输入结束。Consumer
类):
WordFrequencyCounterWithQueue
类):
HashMap
。通过这种方式,我们利用双端阻塞队列实现了线程安全的无界流分词和词频统计。
SynchronousQueue
是 Java 并发包 java.util.concurrent
中的一个特殊的阻塞队列,它在多线程编程中有着独特的用途和特性。下面将从多个方面详细介绍 SynchronousQueue
。
SynchronousQueue
与普通的队列不同,它不存储元素。每个插入操作必须等待另一个线程的移除操作,反之亦然。可以将其理解为一个线程之间进行数据传递的“通道”,一个线程将数据放入队列的同时,另一个线程必须立即将其取出,否则放入操作会被阻塞。这种特性使得 SynchronousQueue
非常适合用于线程间的直接数据交换,而不需要额外的缓冲空间。
SynchronousQueue
实现了 BlockingQueue
接口,因此它具备阻塞队列的基本特性,同时也继承了队列的相关操作方法。
SynchronousQueue
有两个构造方法:
SynchronousQueue()
:创建一个非公平模式的 SynchronousQueue
。在非公平模式下,线程获取队列的顺序是不确定的,由操作系统的调度策略决定。SynchronousQueue(boolean fair)
:可以通过传入 true
来创建一个公平模式的 SynchronousQueue
。在公平模式下,线程获取队列的顺序是按照请求的先后顺序进行的,遵循先进先出(FIFO)原则。由于 SynchronousQueue
不存储元素,它的一些方法表现与其他队列有所不同:
put(E e)
:将元素插入队列,如果没有其他线程正在等待获取元素,当前线程会被阻塞,直到有线程来取走该元素。offer(E e)
:尝试将元素插入队列,如果有其他线程正在等待获取元素,则插入成功并返回 true
;否则返回 false
,不会阻塞当前线程。offer(E e, long timeout, TimeUnit unit)
:尝试在指定的时间内将元素插入队列,如果在超时时间内有线程来取走元素,则插入成功并返回 true
;否则返回 false
。take()
:从队列中移除并返回元素,如果没有元素可供移除,当前线程会被阻塞,直到有其他线程插入元素。poll()
:尝试从队列中移除元素,如果有元素可供移除,则移除并返回该元素;否则返回 null
,不会阻塞当前线程。poll(long timeout, TimeUnit unit)
:尝试在指定的时间内从队列中移除元素,如果在超时时间内有元素可供移除,则移除并返回该元素;否则返回 null
。下面是一个使用 SynchronousQueue
实现生产者 - 消费者模式的示例代码:
import java.util.concurrent.SynchronousQueue;
// 生产者类
class Producer implements Runnable {
private final SynchronousQueue<Integer> queue;
public Producer(SynchronousQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("生产者生产: " + i);
// 将元素放入队列
queue.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// 消费者类
class Consumer implements Runnable {
private final SynchronousQueue<Integer> queue;
public Consumer(SynchronousQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
// 从队列中取出元素
Integer item = queue.take();
System.out.println("消费者消费: " + item);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class SynchronousQueueExample {
public static void main(String[] args) {
// 创建 SynchronousQueue
SynchronousQueue<Integer> queue = new SynchronousQueue<>();
// 创建生产者和消费者线程
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
// 启动线程
producerThread.start();
consumerThread.start();
}
}
Producer
类):在 run
方法中,生产者循环生产 5 个元素,并使用 put
方法将元素放入 SynchronousQueue
中。如果没有消费者线程来取走元素,生产者线程会被阻塞。Consumer
类):在 run
方法中,消费者循环从 SynchronousQueue
中取出元素。如果队列中没有元素,消费者线程会被阻塞,直到生产者线程放入元素。SynchronousQueueExample
类):创建 SynchronousQueue
对象,并启动生产者和消费者线程,实现了线程间的直接数据交换。SynchronousQueue
常用于 Executors.newCachedThreadPool()
方法创建的线程池中。由于该队列不存储元素,当有新的任务提交时,如果没有空闲线程,线程池会创建新的线程来处理任务,从而实现高效的任务处理。SynchronousQueue
。例如,一个线程生成数据后立即传递给另一个线程进行处理。SynchronousQueue
不存储元素,它的吞吐量通常比其他队列要低,因为每次插入和移除操作都需要等待另一个线程的配合。SynchronousQueue
时,需要确保生产者和消费者线程的协调,避免出现死锁或长时间阻塞的情况。