Java執行緒學習 DelayQueue的應用
阿新 • • 發佈:2019-01-25
DelayQueue
是一個無界的BlockingQueue,用於放置實現了Delayed介面的物件,其中的物件只能在其到期時才能從佇列中取走。這種佇列是有序的,即隊頭物件的延遲到期時間最長。注意:不能將null元素放置到這種佇列中。
Delayed
一種混合風格的介面,用來標記那些應該在給定延遲時間之後執行的物件。
此介面的實現必須定義一個 compareTo 方法,該方法提供與此介面的 getDelay 方法一致的排序。
下面的程式碼模擬一個考試的日子,考試時間為120分鐘,30分鐘後才可交卷,當時間到了,或學生都交完捲了者考試結束。執行緒的關閉參考Java程式設計思想中例子,將exec傳給Student的一個內部類,通過他來關閉。
- package com.woxiaoe.study.thread;
- import java.util.Random;
- import java.util.concurrent.DelayQueue;
- import java.util.concurrent.Delayed;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- /**
- * 模擬考試,時間為120分鐘,學生可以再30分鐘後交卷,
- * 當學生都交完了 或 時間到者考試結束
- * @author 小e
- *
- * 2010-4-30 下午11:14:25
- */
- class Student implements Runnable,Delayed{
- private String name;
- private long submitTime;//交卷時間
- private long workTime;//考試時間
- public Student() {
- // TODO Auto-generated constructor stub
- }
- public Student(String name, long
- super();
- this.name = name;
- workTime = submitTime;
- //都轉為轉為ns
- this.submitTime = TimeUnit.NANOSECONDS.convert(submitTime, TimeUnit.MILLISECONDS) + System.nanoTime();
- }
- @Override
- public void run() {
- System.out.println(name + " 交卷,用時" + workTime/100 + "分鐘");
- }
- @Override
- public long getDelay(TimeUnit unit) {
- return unit.convert(submitTime - System.nanoTime(), unit.NANOSECONDS);
- }
- @Override
- public int compareTo(Delayed o) {
- Student that = (Student) o;
- return submitTime > that.submitTime?1:(submitTime < that.submitTime ? -1 : 0);
- }
- public static class EndExam extends Student{
- private ExecutorService exec;
- public EndExam(int submitTime,ExecutorService exec) {
- super(null,submitTime);
- this.exec = exec;
- }
- @Override
- public void run() {
- exec.shutdownNow();
- }
- }
- }
- class Teacher implements Runnable{
- private DelayQueue<Student> students;
- private ExecutorService exec;
- public Teacher(DelayQueue<Student> students,ExecutorService exec) {
- super();
- this.students = students;
- this.exec = exec;
- }
- @Override
- public void run() {
- try {
- System.out.println("考試開始……");
- while (!Thread.interrupted()) {
- students.take().run();
- }
- System.out.println("考試結束……");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public class Exam {
- static final int STUDENT_SIZE = 45;
- public static void main(String[] args) {
- Random r = new Random();
- DelayQueue<Student> students = new DelayQueue<Student>();
- ExecutorService exec = Executors.newCachedThreadPool();
- for(int i = 0; i < STUDENT_SIZE; i++){
- students.put(new Student("學生" + ( i + 1), 3000 + r.nextInt(9000)));
- }
- students.put(new Student.EndExam(12000,exec));//1200為考試結束時間
- exec.execute(new Teacher(students, exec));
- }
- }