1. 前言
来点小牢骚吧!笔者半夜又睡不着了,百无聊赖,又不想打开力扣。最近发现写博客真的是一种缓解压力的好方式,他能把你所会的,所学的一起输出给大众看(虽然可能也没人看罢)但是看着自己的知识输出在大众视野下终归让人感到心安,笔者也会慢慢把这半年自己的笔记输出于大众。一般面试的手撕分很多种 SQL、力扣、还有就是Java的实操,今天也是闲着没事,来记录一下实操中的经典题——多线程相关的题目
2. 回到正题
先让AI帮我找了一下最近多线程相关的题目
(1)手写生产者-消费者模型 使用wait()
/notify()
或BlockingQueue
实现
(2)多线程顺序打印ABC 3个线程按顺序循环打印A、B、C各10次
(3)CAS原理及ABA问题 手写一个基于AtomicInteger
的计数器,并解释ABA问题的解决方案(如AtomicStampedReference
)
(4)手写死锁代码——这个笔者写过,打算偷个懒用以前的代码了
(5)交替打印奇偶数 两个线程交替打印1~100的奇数和偶数(使用wait()
/notify()
或Lock
)
3.
(1)来一个经典思路代码很简单我就不讲了
public class ProducerConsumerByWaitNotify {
private final Queue<Integer> queue = new LinkedList<>();
private final int maxSize;
public ProducerConsumerByWaitNotify(int maxSize){
this.maxSize = maxSize;
}
public void producer(int element) throws InterruptedException{
synchronized (queue){
while (queue.size() == maxSize){
queue.wait();
}
queue.add(element);
queue.notifyAll();
}
}
public void consumer(int element) throws InterruptedException{
synchronized (queue){
while (queue.isEmpty()){
queue.wait();
}
queue.remove();
queue.notifyAll();
}
}
}
BlockingQueue实现
public class ProducerConsumerByBlockingQueue {
private final ArrayBlockingQueue arrayBlockingQueue;
public ProducerConsumerByBlockingQueue(int maxSize){
arrayBlockingQueue = new ArrayBlockingQueue<Integer>(maxSize);
}
public void producer(int element) throws InterruptedException{
arrayBlockingQueue.put(element);
}
public void consumer(int element) throws InterruptedException{
arrayBlockingQueue.take();
}
}