public class Student implements Runnable,Delayed{private String name; //姓名private long costTime;//做試題的時間private long finishedTime;//完成時間public Student(String name, long costTime) {this. name = name;this. costTime= costTime;finishedTime = costTime + System. currentTimeMillis();}@Overridepublic void run() {System. out.println( name + " 交卷,用時" + costTime /1000);}@Overridepublic long getDelay(TimeUnit unit) {return ( finishedTime - System. currentTimeMillis());}@Overridepublic int compareTo(Delayed o) {Student other = (Student) o;return costTime >= other. costTime?1:-1;}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
然后在構造一個教師對象對學生進行考試
public class Teacher {static final int STUDENT_SIZE = 30;public static void main(String[] args) throws InterruptedException {Random r = new Random();//把所有學生看做一個延遲隊列DelayQueue<Student> students = new DelayQueue<Student>();//構造一個線程池用來讓學生們“做作業”ExecutorService exec = Executors.newFixedThreadPool(STUDENT_SIZE);for ( int i = 0; i < STUDENT_SIZE; i++) {//初始化學生的姓名和做題時間students.put( new Student( "學生" + (i + 1), 3000 + r.nextInt(10000)));}//開始做題while(! students.isEmpty()){exec.execute( students.take());}exec.shutdown();}
}
BlockingQueue<String> unbounded = new LinkedBlockingQueue<String>();
BlockingQueue<String> bounded = new LinkedBlockingQueue<String>(1024);
bounded.put("Value");
String value = bounded.take();
public class PriorityElement implements Comparable<PriorityElement> {
private int priority;//定義優先級
PriorityElement(int priority) {//初始化優先級this.priority = priority;
}
@Override
public int compareTo(PriorityElement o) {//按照優先級大小進行排序return priority >= o.getPriority() ? 1 : -1;
}
public int getPriority() {return priority;
}
public void setPriority(int priority) {this.priority = priority;
}
@Override
public String toString() {return "PriorityElement [priority=" + priority + "]";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
然后我們把這些元素隨機設置優先級放入隊列中
public class PriorityBlockingQueueExample {
public static void main(String[] args) throws InterruptedException {PriorityBlockingQueue<PriorityElement> queue = new PriorityBlockingQueue<>();for (int i = 0; i < 5; i++) {Random random=new Random();PriorityElement ele = new PriorityElement(random.nextInt(10));queue.put(ele);}while(!queue.isEmpty()){System.out.println(queue.take());}
}
}