共計 1197 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 中可以使用 BlockingQueue
接口來實現阻塞隊列。BlockingQueue
接口繼承自 Queue
接口,提供了阻塞隊列的基本操作方法,并新增了一些阻塞等待的方法。
常用的 BlockingQueue
的實現類有:
ArrayBlockingQueue
:基于數組的有界阻塞隊列。LinkedBlockingQueue
:基于鏈表的可選有界或無界阻塞隊列。PriorityBlockingQueue
:支持優先級排序的無界阻塞隊列。DelayQueue
:延遲隊列,元素只有在其指定的延遲時間到期時才能出隊列。SynchronousQueue
:容量為 0 的阻塞隊列,用于線程間直接交換數據。
下面是使用 ArrayBlockingQueue
實現阻塞隊列的示例代碼:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExample {public static void main(String[] args) {// 創建一個容量為 10 的阻塞隊列
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生產者線程
Thread producer = new Thread(() -> {try {for (int i = 0; i < 10; i++) {queue.put(i); // 將元素放入隊列
System.out.println("Produced: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {e.printStackTrace();
}
});
// 消費者線程
Thread consumer = new Thread(() -> {try {for (int i = 0; i < 10; i++) {int num = queue.take(); // 從隊列中取出元素
System.out.println("Consumed: " + num);
Thread.sleep(2000);
}
} catch (InterruptedException e) {e.printStackTrace();
}
});
// 啟動生產者和消費者線程
producer.start();
consumer.start();
try {// 等待生產者和消費者線程執行完畢
producer.join();
consumer.join();} catch (InterruptedException e) {e.printStackTrace();
}
}
}
在上述示例中,生產者線程通過 put()
方法將元素放入隊列,如果隊列已滿,則會阻塞等待;消費者線程通過 take()
方法從隊列中取出元素,如果隊列為空,則會阻塞等待。
丸趣 TV 網 – 提供最優質的資源集合!
正文完