import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
public class Main2 {
public static void main(String[] args) {
ArrayBlockingQueue<Milke> arrayBlockingQueue = new ArrayBlockingQueue<Milke>(100);
for (int i = 0; i < 10; i++) {
new Thread(new Producer(arrayBlockingQueue), i + "號生產者").start();
}
for (int i = 0; i < 10; i++) {
new Thread(new Consumer(arrayBlockingQueue), i + "消費者").start();
}
}
}
class Milke {}
class Consumer implements Runnable{
private ArrayBlockingQueue<Milke> queue;
public Consumer(ArrayBlockingQueue<Milke> queue){this.queue = queue;}
@Override
public void run() {
while (true) {
consume();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void consume() {
try{
queue.take();
System.out.println(Thread.currentThread().getName() + " : 消費了一個元素,queue剩餘:" + queue.size());
}catch (Exception e) {
e.printStackTrace();
}
}
}
class Producer implements Runnable{
private ArrayBlockingQueue<Milke> queue;
public Producer(ArrayBlockingQueue<Milke> queue){this.queue = queue;}
@Override
public void run() {
while(true) {
produce();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void produce() {
try{
queue.put(new Milke());
System.out.println(Thread.currentThread().getName() + " : 放入了一個元素,queue剩餘:" + queue.size());
} catch(Exception e) {
e.printStackTrace();
}
}
}
寫法:
1 主類裏面有一個阻塞隊列,消費者,生產者也有一個私有阻塞隊列,通過構造器傳參把主類的隊列讓消費者和生產者得到
2 消費者c 生產者p,c 、p都實現runnable接口重寫run方法,run方法寫死循環,c裏面調c的私有消費方法,p裏面調p的私有生產方法
3 消費者 直接調blockingQueue的take ,記得trycatch,生產者直接調blockingQueue的put,打印剩餘元素個數
4 主類裏面用thread 構造器傳入c p 對象,並傳入線程名稱,循環啓動,記得先new 生產者再new消費者
原理:
源碼:
/**
* Inserts the specified element at the tail of this queue, waiting
* for space to become available if the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
/**
* Extracts element at current take position, advances, and signals.
* Call only when holding lock.
*/
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
- 1 阻塞對列:ArrayBlockingQueue 的插入和取出對應有相應的併發安全的方法:take(消費) put(取出)
- 前提原理:兩個型號量 un_empty 和 un_full un_empty (消費者線程用的信號量)不鎖的時候消費者線程可以消費反正阻塞的時候不能消費,un_full(生產者用的信號量)不鎖的時候生產者可以生產,反之阻塞的時候不能生產。
- take的時候如果有值就會取,取完喚醒”un_full“的信號量(暗示producer隊列現在有空缺了(不滿),可以放了),如果沒有值就會阻塞”un_empty“的信號量(暗示consumer線程現在沒值可取了,等等再來拿吧),put的時候滿了就阻塞un_full,(暗示producer線程別放了,等等吧),put的時候如果隊列沒滿,還可以放就會加元素,同時喚醒”un_empty“(暗示消費者線程可以消費了)
畫個圖: