PriorityBlockingQueue

package com.bjsxt.base.coll013;

 

public class Task implements Comparable<Task>{

 

private int id ;

private String name;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

 

@Override

public int compareTo(Task task) {

// TODO Auto-generated method stub  

        // sort by id in ascending order  

        //If the id of the object itself is greater than the incoming object id,  

        //The return value is a positive number, that is, ascending order  

        //The return value is a negative number, that is, the descending order  

//      if(id>o.getId()) {  

//          return 1;  

//      } else if(id==o.getId()) {  

//          return 0;  

//      }  

//      return -1;  

//      return name.compareTo(o.getName());  

        if(this.id > task.id) {  

            return -1;  

        } else if(this.id == task.id) {  

            return 0;  

        }  

        return 1;  

    }  

public String toString(){

return this.id + "," + this.name;

 

}

 

}

 

 

package com.bjsxt.base.coll013;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @author Administrator
 *PriorityBlockingQueue: Priority-based blocking queue. For an unbounded queue, the queue object must implement the Comparable interface.
 *Note: Adding an element will not be sorted, and the value will be compared only when the task method is called to get the number of rows.
 */
public class UsePriorityBlockingQueue {

	
	public static void main(String[] args) throws Exception{
		
		
		PriorityBlockingQueue<Task> q = new PriorityBlockingQueue<Task>();
		
		Task t1 = new Task();
		t1.setId (40);
		t1.setName("id为3");
		Task t2 = new Task();
		t2.setId(30);
		t2.setName("id为4");
		Task t3 = new Task();
		t3.setId(10);
		t3.setName("id为1");
		
		//return this.id > task.id ? 1 : 0;
		q.add(t2);	//4
		q.add(t1);	//3
		q.add(t3);  //1
		
		// 1 3 4
		System.out.println("容器:" + q);
		System.out.println(q.take().getId());
		//System.out.println("Container: " + q);
		System.out.println(q.take().getId());
		System.out.println(q.take().getId());
		

		
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326186929&siteId=291194637