阻塞佇列-自定義
阿新 • • 發佈:2020-07-14
參考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(); } }