package thread.forkjoinpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Main3 {
static class Event implements Comparable<Event>{
private int id;
private int priority;
/**
* @param id
* @param priority
*/
public Event(int id, int priority) {
this.id = id;
this.priority = priority;
}
public int compareTo(Event o) {
if(o==null) throw new IllegalArgumentException();
if(this.priority>o.priority) return 1;
else if(this.priority<o.priority) return -1;
return 0;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Event [id=" + id + ", priority=" + priority + "]";
}
}
static class Run implements Runnable{
private PriorityBlockingQueue<Event> queue;
/**
* @param queue
*/
public Run(PriorityBlockingQueue<Event> queue) {
this.queue = queue;
}
public void run() {
for (int i = 10; i > 0; i--) {
Event event = new Event(i, i);
queue.add(event);
}
}
}
public static void main(String[] args) {
PriorityBlockingQueue<Event> queue = new PriorityBlockingQueue<Event>();
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
Run run = new Run(queue);
newCachedThreadPool.execute(run);
newCachedThreadPool.shutdown();
try {
boolean awaitTermination = newCachedThreadPool.awaitTermination(10, TimeUnit.SECONDS);
if(awaitTermination){
System.out.println("任務結束");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(queue);
for (int i = 0; i < queue.size(); i++) {
System.out.println(queue.size());
Event poll = queue.poll();
System.out.println(queue.size());
System.out.println("結果:"+poll);
}
}
}
任務結束
[Event [id=1, priority=1], Event [id=2, priority=2], Event [id=5, priority=5], Event [id=4, priority=4], Event [id=3, priority=3], Event [id=9, priority=9], Event [id=6, priority=6], Event [id=10, priority=10], Event [id=7, priority=7], Event [id=8, priority=8]]
10
9
結果:Event [id=1, priority=1]
9
8
結果:Event [id=2, priority=2]
8
7
結果:Event [id=3, priority=3]
7
6
結果:Event [id=4, priority=4]
6
5
結果:Event [id=5, priority=5]
這個為什麼只輸出了5個記錄?但是集合的大小是對的
for (int i = 0; i < queue.size(); i++) {
System.out.println(queue.size());
Event poll = queue.poll();//每次poll一個,queue長度在不斷改變,當移除5個,的時候queue.size()就只有5了,而這時候i也是5,for條件(i<queue.size())不成立,退出循環,所以就移除了5個,也就是一半
System.out.println(queue.size());
System.out.println("結果:"+poll);
}
改成
for (int i = queue.size()-1; i >=0; i--) {
System.out.println(queue.size());
Event poll = queue.poll();
System.out.println(queue.size());
System.out.println("結果:"+poll);
}
或者
while(queue.size()>0){
System.out.println(queue.size());
Event poll = queue.poll();
System.out.println(queue.size());
System.out.println("結果:"+poll);
}
如果有幫助,記得采納一下哦