Queue接口與List
隊列是一種數據結構.它有兩個基本操作
add 增加一個元索 如果隊列已滿
remove 移除並返回隊列頭部的元素 如果隊列為空
element 返回隊列頭部的元素 如果隊列為空
offer 添加一個元素並返回true 如果隊列已滿
poll 移除並返問隊列頭部的元素 如果隊列為空
peek 返回隊列頭部的元素 如果隊列為空
put 添加一個元素 如果隊列滿
take 移除並返回隊列頭部的元素 如果隊列為空
remove
阻塞隊列的操作可以根據它們的響應方式分為以下三類
注意
還有帶超時的offer和poll方法變種
boolean success = q
嘗試在
Object head = q
如果在
最後
ncurrent包提供了阻塞隊列的
ArrayBlockingQueue在構造時需要指定容量
PriorityBlockingQueue是一個帶優先級的隊列
最後
Java代碼
public interface Delayed extends Comparable<Delayed> {
long getDelay(TimeUnit unit);
}
public interface Delayed extends Comparable<Delayed> {
long getDelay(TimeUnit unit);
}
放入DelayQueue的元素還將要實現compareTo方法
下面的實例展示了如何使用阻塞隊列來控制線程集
Java代碼
public class BlockingQueueTest {
public static void main(String[] args) {
Scanner in = new Scanner(System
System
String directory = in
System
String keyword = in
final int FILE_QUEUE_SIZE =
final int SEARCH_THREADS =
// 基於ArrayBlockingQueue的阻塞隊列
BlockingQueue<File> queue = new ArrayBlockingQueue<File>(
FILE_QUEUE_SIZE);
//只啟動一個線程來搜索目錄
FileEnumerationTask enumerator = new FileEnumerationTask(queue
new File(directory));
new Thread(enumerator)
//啟動
for (int i =
new Thread(new SearchTask(queue
}
}
class FileEnumerationTask implements Runnable {
//啞元文件對象
public static File DUMMY = new File(
private BlockingQueue<File> queue;
private File startingDirectory;
public FileEnumerationTask(BlockingQueue<File> queue
this
this
}
public void run() {
try {
enumerate(startingDirectory);
queue
} catch (InterruptedException e) {
}
}
// 將指定目錄下的所有文件以File對象的形式放入阻塞隊列中
public void enumerate(File directory) throws InterruptedException {
File[] files = directory
for (File file : files) {
if (file
enumerate(file);
else
//將元素放入隊尾
queue
}
}
}
class SearchTask implements Runnable {
private BlockingQueue<File> queue;
private String keyword;
public SearchTask(BlockingQueue<File> queue
this
this
}
public void run() {
try {
boolean done = false;
while (!done) {
//取出隊首元素
File file = queue
if (file == FileEnumerationTask
//取出來後重新放入
queue
done = true;
} else
search(file);
}
} catch (IOException e) {
e
} catch (InterruptedException e) {
}
}
public void search(File file) throws IOException {
Scanner in = new Scanner(new FileInputStream(file));
int lineNumber =
while (in
lineNumber++;
String line = in
if (ntains(keyword))
System
line);
}
in
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26657.html