帮忙看看这个程序的输出?

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个记录?但是集合的大小是对的

查看全部
mymailmjj_1984
missing_mjj
2015/07/25 16:18
  • java
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复