今天就跟大家聊聊有關(guān)JAVA中怎么使用Lock和Condition手寫阻塞隊(duì)列,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
創(chuàng)新互聯(lián)建站10多年成都企業(yè)網(wǎng)站建設(shè)服務(wù);為您提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)頁(yè)設(shè)計(jì)及高端網(wǎng)站定制服務(wù),成都企業(yè)網(wǎng)站建設(shè)及推廣,對(duì)成都護(hù)欄打樁機(jī)等多個(gè)行業(yè)擁有豐富的營(yíng)銷推廣經(jīng)驗(yàn)的網(wǎng)站建設(shè)公司。
package com.study; import java.util.Random; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class BlockingQueueDemo { public static void main(String[] args) { BlockingQueueDemo blockingQueueDemo = new BlockingQueueDemo(); final BlockingQueueClass blockingQueueClass = blockingQueueDemo.new BlockingQueueClass(); Thread thread = new Thread(new Runnable() { @Override public void run() { while(true){ int value = new Random().nextInt(); System.out.println("準(zhǔn)備存數(shù)據(jù)了"); blockingQueueClass.put(value); System.out.println("已經(jīng)存好數(shù)據(jù)了"); } } }); thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { while(true){ System.out.println("準(zhǔn)備取數(shù)據(jù)了"); Object value = blockingQueueClass.take(); System.out.println("取到的數(shù)據(jù)為:" + value); } } }); thread2.start(); } class BlockingQueueClass{ Lock lock = new ReentrantLock(); Condition notFullCondition = lock.newCondition(); Condition notEmptyCondition = lock.newCondition(); Object[] items = new Object[100]; private int putLength,takeLength,count; public void put(Object object){ lock.lock(); try { while(count == items.length){ try { notFullCondition.await(); } catch (InterruptedException error) { error.printStackTrace(); } } items[putLength] = object; if(++putLength == items.length){ putLength = 0; } ++count; notEmptyCondition.signal(); } catch (Exception e) { e.printStackTrace(); } finally{ lock.unlock(); } } public Object take(){ Object object = new Object(); lock.lock(); try { while(count == 0){ try { notEmptyCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } object = items[takeLength]; if(++takeLength == items.length){ takeLength = 0; } --count; notFullCondition.signal(); } catch (Exception e) { e.printStackTrace(); lock.unlock(); } return object; } } }
看完上述內(nèi)容,你們對(duì)JAVA中怎么使用Lock和Condition手寫阻塞隊(duì)列有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。