標籤:highlight 技術分享 生產者 producer 生產 div ima pre util
想大致瞭解多線程的相關知識的可以先看看這篇文章。
線程各個狀態的變化。
看下wait
import java.util.concurrent.ArrayBlockingQueue;/** * 生產者-消費者 * * @author zzs . * @since 2018/3/24 */public class BlockingQueueTest { private int size = 20; private ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(size); public static void main(String[] args) { BlockingQueueTest test = new BlockingQueueTest(); Producer producer = test.new Producer(); Consumer consumer = test.new Consumer(); producer.start(); consumer.start(); } class Consumer extends Thread { @Override public void run() { while (true) { try { //從阻塞隊列中取出一個元素 blockingQueue.take(); System.out.println("隊列剩餘" + blockingQueue.size() + "個元素"); } catch (InterruptedException e) { } } } } class Producer extends Thread { @Override public void run() { while (true) { try { //向阻塞隊列中插入一個元素 blockingQueue.put(1); System.out.println("隊列剩餘空間:" + (size - blockingQueue.size())); } catch (InterruptedException e) { } } } }}
Java核心技術點之多線程2