Java核心技術點之多線程2

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.