阻塞队列-自定义
参考ArrayBlockingQueue
import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class DemoBlockList { private ReentrantLock lock = new ReentrantLock(); private Condition isEmpty = lock.newCondition(); private Condition isFull = lock.newCondition(); private List<String> list; private int count; public DemoBlockList(int max) { this.list = new ArrayList<>(max); this.count = max; } public void put(String val) throws InterruptedException { ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (list.size() == count) { this.isFull.await(); } list.add(val); count++; this.isEmpty.signalAll(); } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } } public String take() throws InterruptedException { ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (list.size() == 0) { this.isEmpty.await(); } this.isFull.signalAll(); count--; return list.remove(0); } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } return null; } }
public static void main(String[] args) { DemoBlockList demoBlockList = new DemoBlockList(10); List<Thread> pList = new ArrayList<>(); for (int i = 0; i < 10; i++) { Thread p = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { try { Thread.sleep(1000); String val = Thread.currentThread().getName() + ",值=" + i; demoBlockList.put(val); System.out.println(Thread.currentThread().getName() + "存储数据value=" + val); } catch (InterruptedException e) { e.printStackTrace(); } i++; } } }); p.setName("生产者线程-" + i); pList.add(p); } for (int i = 0; i < 10; i++) { pList.get(i).start(); } List<Thread> cList = new ArrayList<>(); for (int i = 0; i < 10; i++) { Thread c = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { try { Thread.sleep(500); String s = demoBlockList.take(); System.out.println(Thread.currentThread().getName() + "-获得数据value=" + s); } catch (InterruptedException e) { e.printStackTrace(); } i++; } } }); c.setName("消费者线程-" + i); cList.add(c); } for (int i = 0; i < 10; i++) { cList.get(i).start(); } }
收藏文章数量从多到少与“把书读薄”是一个道理