DelayQueue use example

In the process of learning Java multithreaded concurrent development, we understand the main role of DelayQueue class: it is an unbounded BlockingQueue, which is used to place objects that implement the Delayed interface, in which objects can only be removed from the queue when they expire. This kind of queue is ordered, that is, the delayed expiration time of the queue head object is the longest. Note: null elements cannot be placed in this queue.

Delayed, a hybrid style interface, is used to mark objects that should be executed after a given delay time. The implementation of this interface must define a compareTo method that provides a sort consistent with the getDelay method of this interface.

I saw some examples on the Internet, found some problems in some examples, and made some modifications, hoping to help you understand.

Chinese people all like K songs. Most people have a singer's dream in their hearts. Especially in their school days, they all like to form groups to sing on KTV. Once they sing for an afternoon, they all sing happily. In the annual Double 11, many single dogs began to form groups to sing on KTV. Then how can KTV charge time by program at this time? The simulation code is as follows:

public class KTV implements Runnable{
    private DelayQueue<KTVConsumer> queue = new DelayQueue<>();

    public void begin(String name,String boxNum,int money){

        KTVConsumer man = new KTVConsumer(name,boxNum,20l*money+System.currentTimeMillis());
        System.out.println(man.getName()+" And others handed in."+money+"Money, enter"+man.getBoxNum()+"Box No.,start K song...");
        this.queue.add(man);
    }

    public void end(KTVConsumer man){
        System.out.println(man.getName()+" Where others are located"+man.getBoxNum()+"Box No.,Time out...");
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
            try {
                KTVConsumer man = queue.take();
                end(man);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]){
        try{
            System.out.println("KTV Normal business");
            System.out.println("================================");
            KTV  ktv = new KTV();
            Thread sing = new Thread(ktv);
            sing.start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ktv.begin("Zhang San", "111", 500);
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    ktv.begin("Li Si", "666", 200);
                }
            }).start();

            Thread.sleep(2000);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ktv.begin("Wang Wu", "888", 100);
                    System.out.println("================================");
                }
            }).start();

        }
        catch(Exception ex){

        }

    }
}
public class KTVConsumer implements Delayed{
    private String name;
    //Deadline
    private long endTime;
    //Box number
    private String boxNum;

    public KTVConsumer(String name,String boxNum,long endTime){
        this.name=name;
        this.boxNum=boxNum;
        this.endTime=endTime;
    }

    public String getName(){
        return this.name;
    }

    public String getBoxNum(){
        return this.boxNum;
    }

    /**
     * Used to determine whether the deadline is up
     */
    @Override
    public long getDelay(TimeUnit unit) {
        // TODO Auto-generated method stub
        return unit.convert(endTime - System.currentTimeMillis(),  TimeUnit.MILLISECONDS);
    }

    /**
     * Comparisons and Sorting
     */
    @Override
    public int compareTo(Delayed o) {
        // TODO Auto-generated method stub
        if(o == null || ! (o instanceof KTVConsumer)) return 1;
        if(o == this) return 0;
        KTVConsumer s = (KTVConsumer)o;
        return endTime - s.endTime > 0 ? 1 :(endTime - s.endTime == 0 ? 0 : -1);
    }
}

The results are as follows:

KTV normally operates
================================
Zhang San and others paid 500 yuan, entered Box 111, and began K song....................................................
Li Si and others paid 200 yuan, entered box 666, and began K song......................................................
Wang Wu and others paid 100 yuan and went to Box 888 to begin K song....................................................
================================
It's time for Lisi and others to be in box 666.
The time is up in Box 888, where Wang Wu and others are located.
It's time for box 111, where Zhang San and others are located. It's time for you to go to _________.

Keywords: Java

Added by teege84 on Fri, 24 May 2019 01:21:33 +0300