亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ArrayBlockingQueue NoSuchElementException

ArrayBlockingQueue NoSuchElementException

HUH函數 2021-10-06 10:50:29
僅供學習,我編寫了以下代碼用于自定義線程池引用和編輯此處顯示的代碼。如代碼所示,我將 ArrayBlockingQueue 用于任務隊列。代碼:import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;public class ThreadPoolService {    private final BlockingQueue<Runnable> taskQueue;    private final int corePoolSize;    private ThreadPoolService(int corePoolSize) {        this.corePoolSize = corePoolSize;        this.taskQueue = new ArrayBlockingQueue<>(corePoolSize);        ThreadPool[] threadPool = new ThreadPool[corePoolSize];        for (int i = 0; i < corePoolSize; i++) {            threadPool[i] = new ThreadPool();            threadPool[i].start();        }    }    public static ThreadPoolService newFixedThreadPool(int size) {        return new ThreadPoolService(size);    }    public void execute(Runnable task) {        try {            taskQueue.offer(task, 10, TimeUnit.SECONDS);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    private class ThreadPool extends Thread {        Runnable task;        @Override        public void run() {            while (true) {                try {                    while (!taskQueue.isEmpty()) {                        task = taskQueue.remove();                        task.run();                    }                } catch (RuntimeException ex) {                    ex.printStackTrace();                }            }        }    }    public static void main(String[] args) {        ThreadPoolService pool = ThreadPoolService.newFixedThreadPool(10);        Runnable task1 = () -> {            System.out.println(" Wait for sometime: -> " + Thread.currentThread().getName());            try {                TimeUnit.SECONDS.sleep(2);            } catch (InterruptedException e) {                e.printStackTrace();            }此代碼有時運行良好,有時會出錯。
查看完整描述

3 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

在“while”檢查和實際刪除之間,隊列可能會被另一個線程修改,這可能會導致您提到的錯誤。這就是所謂的“競爭條件”。

因此,為了解決這個問題,您需要一種方法來阻止其他線程對隊列的訪問,或者通過“鎖定”,使用帶有共享鎖定對象的“同步”塊。或者簡單地通過“輪詢”而不是刪除。


查看完整回答
反對 回復 2021-10-06
  • 3 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號