Home >Java >javaTutorial >Java multi-threaded concurrent development about the use of DelayQueue

Java multi-threaded concurrent development about the use of DelayQueue

黄舟
黄舟Original
2017-09-20 09:56:141179browse

This article mainly introduces the use examples of DelayQueue in Java multi-threaded concurrent development in detail. It has certain reference value. Interested friends can refer to it

In learning Java multi-threaded concurrent development In the process, I learned that the main function of the DelayQueue class is: it is an unbounded BlockingQueue, used to place objects that implement the Delayed interface. The objects in it can only be removed from the queue when they expire. This kind of queue is ordered, that is, the head object has the longest delayed expiration time. Note: null elements cannot be placed into this kind of queue.

Delayed, a mixed-style interface used to mark objects that should be executed after a given delay time. Implementations of this interface must define a compareTo method that provides ordering consistent with this interface's getDelay method.

I saw some examples on the Internet and found that some of them had some problems, so I made some modifications. I hope it can help everyone understand.

Chinese people all like karaoke. Most people have a dream of being a singer in their hearts, especially when they were students. Everyone likes to form a group to sing in KTV. They sing all afternoon and everyone enjoys it. . It’s the annual Double 11 again, and many singles have begun to form groups and come to KTV to sing. So how does KTV charge time through the 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()+" 等人交了"+money+"元钱,进入"+man.getBoxNum()+"号包厢,开始K歌...");
    this.queue.add(man);
  }

  public void end(KTVConsumer man){
    System.out.println(man.getName()+" 等人所在的"+man.getBoxNum()+"号包厢,时间到...");
  }

  @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正常营业");
      System.out.println("================================");
      KTV ktv = new KTV();
      Thread sing = new Thread(ktv);
      sing.start();
      new Thread(new Runnable() {
        @Override
        public void run() {
          ktv.begin("张三", "111", 500);
        }
      }).start();

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

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

    }
    catch(Exception ex){

    }

  }
}
public class KTVConsumer implements Delayed{
  private String name;
  //截止时间
  private long endTime;
  //包厢号
  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;
  }

  /**
   * 用来判断是否到了截止时间
   */
  @Override
  public long getDelay(TimeUnit unit) {
    // TODO Auto-generated method stub
    return unit.convert(endTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
  }

  /**
   * 相互比较排序用
   */
  @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 running results are as follows:


KTV正常营业
================================
张三 等人交了500元钱,进入111号包厢,开始K歌...
李四 等人交了200元钱,进入666号包厢,开始K歌...
王五 等人交了100元钱,进入888号包厢,开始K歌...
================================
李四 等人所在的666号包厢,时间到...
王五 等人所在的888号包厢,时间到...
张三 等人所在的111号包厢,时间到...

The above is the detailed content of Java multi-threaded concurrent development about the use of DelayQueue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn