公共類汽車實現可比{我如何排序Java中的ArrayBlockingQueue?
private String company, model;
private int price;
public Cars(String company, String model, int price){
this.company=company;
this.model=model;
this.price=price;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + price;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cars other = (Cars) obj;
if (price != other.price)
return false;
return true;
}
public String toString(){
return String.format("Comapany: %s, Model: %s, Price: %d", this.company, this.model, this.price);
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int compareTo(Object obj) {
return this.price-((Cars)obj).price;
}
}
公共類BlockingQueueExample {
BlockingQueue<Cars> queue;
Random random=new Random();
private boolean running=false;
public BlockingQueueExample(BlockingQueue<Cars> queue){
this.queue=queue;
running=true;
}
public void producer() throws InterruptedException{
while(running){
int add_car=random.nextInt(5);
Cars value=null;
switch(add_car){
case 0:value=new Cars("BMV", "q7", 4000);break;
case 1:value=new Cars("Renault","KWID", 2000);break;
case 2:value=new Cars("Porche","Cayenee", 3000);break;
case 3:value=new Cars("Skoda", "Rapid", 2500);break;
case 4:value=new Cars("Volkswagen", "Ameo", 3500);break;
}
queue.put(value);
System.out.println("PRODUCER "+ value);
System.out.println();
}
}
public void consumer() throws InterruptedException{
while(running){
Thread.sleep(500);
if(random.nextInt(5)==0){
Cars value=queue.take();
//Collections.sort((List<Cars>) queue);
System.out.println("CONSUMER Taken value: "+value +", Queue size: "+queue.size()+"\n"+queue);
System.out.println();
}
}
}
public void stop(){
running=false;
// method to sort queue
System.out.println("Sorted queue:"+"\n"+queue);
}
}
我試圖Arrays.sort(queue.toArray()),集合.sort(queue),doesn; t wok;這是爲明天的演示文稿....有人請welp
首先,標題中沒有必要使用這種語言。其次,我們不知道「welp」是什麼意思。第三,ArrayBlockingQueue是FIFO結構,並不意味着排序。 –