您的位置:首页 > 产品设计 > UI/UE

【java】队列、优先队列、双端队列Deque、链表LinkedList、阻塞队列(Blocking queue)

2015-08-25 15:02 441 查看






package test;

public class HelloWorld {
public static void main(String[] args) {
java.util.Queue<String> queue =
new java.util.LinkedList<String>();
queue.offer("Oklahoma");
queue.offer("Indiana");
queue.offer("Georgia");
queue.offer("Texas");

while (queue.size() > 0)
System.out.println(queue.remove() + " ");
}
}


package test;

import java.util.*;

public class HelloWorld {
public static void main(String[] args) {
//无参数构造方法创建字符串优先队列,因此按照升序从队列中删除
PriorityQueue<String> queue1 = new PriorityQueue<String>();
queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia");
queue1.offer("Texas");

System.out.println("Priority queue using Comparable:");
while (queue1.size() > 0) {
System.out.print(queue1.remove() + " ");
}

//创建一个带指定初始容量和比较器的优先队列。从Collection.reverseOrder()中获得的比较器
//创建优先队列,该方法以逆序对元素排序,因此,字符串以降序从队列中删除
PriorityQueue<String> queue2 = new PriorityQueue<String>(
4, Collections.reverseOrder());
queue2.offer("Oklahoma");
queue2.offer("Indiana");
queue2.offer("Georgia");
queue2.offer("Texas");

System.out.println("\nPriority queue using Comparator:");
while (queue2.size() > 0) {
System.out.print(queue2.remove() + " ");
}
}
}






阻塞队列:

package test;

import java.util.concurrent.*;

public class HelloWorld {
//	对于多线程而言,单个线程使用Thread,多个线程使用线程池。
//	都有其一个基本的格式,只要完成Run()方法编写
private static ArrayBlockingQueue<Integer> buffer =
new ArrayBlockingQueue<Integer>(2);

public static void main(String[] args) {
// Create a thread pool with two threads
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new ProducerTask());
executor.execute(new ConsumerTask());
executor.shutdown();
}

// A task for adding an int to the buffer
private static class ProducerTask implements Runnable {
public void run() {
try {
int i = 1;
while (true) {
System.out.println("Producer writes " + i);
buffer.put(i++); // Add any value to the buffer, say, 1
// Put the thread into sleep
Thread.sleep((int)(Math.random() * 10000));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

// A task for reading and deleting an int from the buffer
private static class ConsumerTask implements Runnable {
public void run() {
try {
while (true) {
System.out.println("\t\t\tConsumer reads " + buffer.take());
// Put the thread into sleep
Thread.sleep((int)(Math.random() * 10000));
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: